Example #1
0
 public function actionDelete($id)
 {
     if (File::model()->deleteByPk($id)) {
         echo "Ajax Success";
         Yii::app()->end();
     }
 }
 public function loadModel($id)
 {
     if (($model = File::model()->findByPk($id)) === null) {
         throw new CHttpException(404, 'Страница не найдена');
     }
     return $model;
 }
Example #3
0
 public function run()
 {
     //if (Yii::app()->request->isAjaxRequest) {
     if (isset($_REQUEST['fid'])) {
         // Delete from database
         $file = File::model()->findByPk($_REQUEST['fid']);
         if (isset($file)) {
             if ($file->delete()) {
                 // Delete file
                 UploadUtils::deleteFile($file, SimpleUploadWidget::$fileDir);
                 $result["result"] = 0;
             } else {
                 $result["result"] = -1;
                 $result["message"] = Yii::t('upload', 'Could not delete file from db');
             }
         } else {
             $result["result"] = -1;
             $result["message"] = Yii::t('upload', 'No file with that fid');
         }
     } else {
         $result["result"] = -1;
         $result["message"] = Yii::t('upload', 'There is no file id (nor db and no session)');
     }
     echo CJSON::encode($result);
     exit(0);
     // To avoid loggers append things to request
     //}
 }
Example #4
0
 public static function deleteFiles($model, $fileDir)
 {
     $files = File::model()->findAll(array('condition' => 'entity=:entity AND EXid=:EXid', 'params' => array(':entity' => get_class($model), ':EXid' => $model->getPrimaryKey())));
     foreach ($files as $file) {
         self::deleteFile($file, $fileDir);
     }
 }
Example #5
0
 public function run()
 {
     if (isset($_REQUEST['fid']) && is_numeric($_REQUEST['fid'])) {
         // Delete from database
         $file = File::model()->findByPk($_REQUEST['fid']);
         if (isset($file)) {
             if ($file->delete()) {
                 // Delete file
                 UploadUtils::deleteFile($file, PlUploadWidget::$fileDir);
                 $result["result"] = 0;
             } else {
                 $result["result"] = -1;
                 $result["message"] = Yii::t('upload', 'Could not delete file from db');
             }
         } else {
             $result["result"] = -1;
             $result["message"] = Yii::t('upload', 'No file with that fid');
         }
     } elseif (isset($_REQUEST['sid']) && is_numeric($_REQUEST['sid'])) {
         // Delete from session
         $sessionFiles = Yii::app()->session['temp_files'];
         $file = File::buildFromArray($sessionFiles[$_REQUEST['sid']]);
         unset($sessionFiles[$_REQUEST['sid']]);
         Yii::app()->session['temp_files'] = $sessionFiles;
         // Delete file
         UploadUtils::deleteFile($file, PlUploadWidget::$tempDir);
         $result["result"] = 0;
     } else {
         $result["result"] = -1;
         $result["message"] = Yii::t('upload', 'There is no file id (nor db and no session)');
     }
     echo CJSON::encode($result);
     exit(0);
     // To avoid loggers append things to request
 }
Example #6
0
 public function getFilesInIds($ids)
 {
     $crit = new CDbCriteria();
     $crit->condition = "dataset_id = :id";
     $crit->params = array(':id' => $this->id);
     $crit->addInCondition("id", $ids);
     return File::model()->findAll($crit);
 }
Example #7
0
 /**
  * Prepares attributes before performing validation.
  */
 protected function beforeValidate($on)
 {
     if (!$this->isNewRecord && File::model()->findbyPk($this->id)->name != $this->name && $this->name != '' && file_exists(Yii::app()->params['filePath'] . $this->name)) {
         $this->addError('name', Yii::t('lan', 'File exists.'));
         return false;
     }
     return true;
 }
Example #8
0
 public function getFiles()
 {
     $attributes = array('id_object' => $this->model->objectId, 'id_parameter' => $this->model->parameterId, 'id_parent_file' => null);
     if ($this->model->instanceId) {
         $attributes['id_instance'] = $this->model->instanceId;
     } else {
         $attributes['id_tmp'] = $this->model->tmpId;
     }
     return File::model()->findAllByAttributes($attributes);
 }
Example #9
0
 protected function handleInternalUrls($url)
 {
     // Handle urls to file
     if (substr($url, 0, 10) === "file-guid-") {
         $guid = str_replace('file-guid-', '', $url);
         $file = File::model()->findByAttributes(array('guid' => $guid));
         if ($file !== null) {
             return $file->getUrl();
         }
     }
     return $url;
 }
Example #10
0
 /**
  * On cron daily run do some cleanup stuff.
  * We delete all files which are not assigned to object_model/object_id
  * within 1 day.
  *
  * @param type $event
  */
 public static function onCronDailyRun($event)
 {
     $cron = $event->sender;
     /**
      * Delete unused files
      */
     $deleteTime = time() - 60 * 60 * 24 * 1;
     // Older than 1 day
     foreach (File::model()->findAllByAttributes(array(), 'created_at < :date AND (object_model IS NULL or object_model = "")', array(':date' => date('Y-m-d', $deleteTime))) as $file) {
         $file->delete();
     }
 }
Example #11
0
 public function actionRotateImage($gitem_id, $direction)
 {
     $model = File::model()->findByPk($gitem_id);
     if (!$model) {
         throw new CHttpException(404);
     }
     if (!Yii::app()->user->checkAccess('album_editGItem', array('item' => $model))) {
         throw new CHttpException(403);
     }
     $this->getModule()->getComponent('image')->rotate($file_path = $model->getAbsolutePath(), $direction);
     $this->getModule()->createThumbnails($file_path, true);
     echo CJSON::encode(array('success' => true));
 }
 public function setPhoto($photos)
 {
     $curModel = get_class($this);
     $curPrimaryKeyValue = $this->{$this->tableSchema->primaryKey};
     $contition = new CDbCriteria();
     $contition->addCondition('record_id=:record_id');
     $contition->addNotInCondition('id', $photos);
     $contition->addCondition('model=:model');
     $contition->params[':record_id'] = $curPrimaryKeyValue;
     $contition->params[':model'] = $curModel;
     File::model()->updateAll(['record_id' => '0'], $contition);
     $condition = new CDbCriteria();
     $condition->addCondition('model=:model');
     $condition->params[':model'] = $curModel;
     File::model()->updateByPk($photos, ['record_id' => $curPrimaryKeyValue], $condition);
 }
Example #13
0
 public function renderDataCell($row)
 {
     if ($this->objectParameter == null) {
         throw new Exception("Не указан ид параметр у колонки с типом Файл");
     }
     $field = $this->name;
     $data = $this->grid->dataProvider->data[$row];
     $value = $data->{$field};
     if ($value != null) {
         $this->htmlOptions = array('class' => 'col-img');
         $f = File::model()->findByPk($value);
         if ($f == null) {
             $value = "";
         } else {
             $link = $f->getUrlPath();
             $fileType = $f->getFileType();
             if ($fileType == null) {
                 $fileType = $f->definitionFileType();
             }
             if ($fileType == File::FILE_IMAGE) {
                 //Если свойством являетеся картинка, то пробуем сделать для неё превью.
                 if ($f->getStatusProcess() == 1) {
                     $memory = @ini_get("memory_limit");
                     if ($memory != null) {
                         $memory = "(" . $memory . ") ";
                     }
                     $value = "<div style='text-align:center'><img src=\"/engine/admin/gfx/msg.png\" title=\"Для данного изображения не может быть сгенирована превью-картинка. Как правило, это связано с ограничением оперативной памяти " . $memory . "на хостинг-площадке.\" alt=\"\"></div>";
                 } else {
                     $idInstance = $data->getIdInstance();
                     $filePreview = $f->getPreview(0, 50, '_da');
                     if ($filePreview == null) {
                         $value = '<b>Открыть текущий файл для просмотра</b>';
                     } else {
                         $value = '<img src="' . $filePreview->getUrlPath() . '" alt="" />';
                     }
                 }
                 $value = '<a rel="daG" target="_blank" href="' . $link . '">' . $value . '</a>';
             } else {
                 $value = '<a target="_blank" href="' . $link . '" title="Открыть текущий файл для просмотра"><i></i></a>';
                 $this->htmlOptions = array('class' => 'col-action-view');
             }
         }
     }
     echo CHtml::openTag('td', $this->htmlOptions);
     echo $value;
     echo '</td>';
 }
Example #14
0
 /**
  * 文件下载
  */
 public function actionDownload()
 {
     $id = Yii::app()->request->getQuery('id');
     $file = File::model()->findByPk($id);
     $name = '';
     $path = '';
     if (!empty($file)) {
         $name = $file->name;
         $path = $file->path;
     }
     //将网页变为下载框,原本是:header("content-type:text/html;charset=utf-8");
     header("content-type:application/x-msdownload");
     //设置下载框上的文件信息
     header("content-disposition:attachment;filename={$name}");
     //readfile("文件路径");从服务器读取文件,该函数才真正实现下载功能,其它的是固定死的
     readfile('./' . $path);
 }
 /**
  * Скачать файл по его ID
  * 
  * @param string $id - ID файла
  * 
  * @return void
  */
 public function actionDownload($alias)
 {
     $file = File::model()->find('t.alias = :alias', array(':alias' => $alias));
     if (empty($file)) {
         throw new CHttpException('404', 'Файл не найден');
     }
     //отключить профайлеры
     $this->disableProfilers();
     if (file_exists($file->path)) {
         // Увеличиваем счетчик
         $file->increaseCounter();
         // Отдаем файл на скачку
         $ext = pathinfo($file->file, PATHINFO_EXTENSION);
         Yii::app()->getRequest()->sendFile($file->title . '.' . $ext, @file_get_contents($file->path), 'application/octet-stream');
     } else {
         throw new CHttpException('404', 'Файл не найден');
     }
 }
Example #16
0
 protected function getFiles()
 {
     if ($this->_files === null) {
         $this->_files = array();
         foreach ($this->getFileObjectParameters() as $objectParam) {
             $attributes = array('id_object' => $this->owner->getIdObject(), 'id_parameter' => $objectParam->id_parameter);
             if ($this->owner->isNewRecord) {
                 $attributes['id_tmp'] = $this->getTmpId();
             } else {
                 $attributes['id_instance'] = $this->owner->getIdInstance();
             }
             $files = File::model()->findAllByAttributes($attributes);
             if ($files) {
                 $this->_files[$objectParam->id_parameter] = $files;
             }
         }
     }
     return $this->_files;
 }
 /**
  * 处理文件(上传下载)事宜
  * Enter description here ...
  */
 public function handle()
 {
     $result = $this->uploader->run(array('path' => Yii::app()->getBasePath() . "/../uploads/file", 'publicPath' => Yii::app()->getBaseUrl() . "/uploads/file"));
     if (!$this->isDeleting()) {
         $file = new File();
         $file->name = $result['name'];
         $file->size = $result['size'];
         $file->addTime = time();
         $file->userId = Yii::app()->user->id;
         $file->path = substr($result['url'], strrpos($result['url'], '/uploads/'));
         $file->save();
         //			error_log(print_r($file));
     } else {
         $file = File::model()->findByAttributes(array('path' => substr($result['url'], strrpos($result['url'], '/uploads/'))));
         if ($file) {
             $file->delete();
         }
     }
     return $file;
 }
Example #18
0
 public function run()
 {
     $files = array();
     $entity = $_REQUEST['entity'];
     $EXid = $_REQUEST['EXid'];
     Yii::trace("FilePanelAction {$entity} {$EXid}");
     // Temporal files in session
     $tempFiles = array();
     $sessionFiles = Yii::app()->session['temp_files'];
     if (isset($sessionFiles)) {
         foreach ($sessionFiles as $f) {
             $tempFiles[] = File::buildFromArray($f);
         }
     }
     if (isset($entity) && isset($EXid)) {
         $files = File::model()->findAll('entity=:entity AND EXid=:EXid', array(':entity' => $entity, ':EXid' => $EXid));
     }
     $files = array_merge($files, $tempFiles);
     $this->getController()->renderPartial('ext.upload.plupload.views.draggableFileList', array('files' => $files));
     exit(0);
     // To avoid loggers append things to request
 }
Example #19
0
 public function getFileClick($id, $time, $type = null)
 {
     $fileInfo = File::model()->findByPk($id);
     if ($fileInfo) {
         $file_url = $fileInfo['url'];
         $total = 0;
         foreach ($file_url as $url) {
             if ($type) {
                 if ($url->type == $type) {
                     if ($time == "day") {
                         return $url->day_click;
                     }
                     if ($time == "month") {
                         return $url->month_click;
                     }
                 }
             }
             $total += $url->day_click;
         }
         return $total;
     }
     return 0;
 }
 /**
  * Returns the static model of the specified AR class.
  * @param string $className active record class name.
  * @return File the static model class
  */
 public static function model($className = __CLASS__)
 {
     return parent::model($className);
 }
 public function actionDelete($id, $fileModel, $recordModel, $multipleImages = 'no')
 {
     switch ($fileModel) {
         case 'GalleryImage':
             $modelName = '\\application\\models\\Place\\GalleryImage';
             break;
         case 'MainGalleryImage':
             $modelName = '\\application\\models\\Place\\MainGalleryImage';
             $thisImage = File::model()->findByPk($id);
             $recordModel::model()->updateByPk($thisImage->recordId, array('mainGalleryImageId' => '0'));
             break;
         case 'MainViewImage':
             $modelName = '\\application\\models\\Place\\MainViewImage';
             $thisViewImage = File::model()->findByPk($id);
             $recordModel::model()->updateByPk($thisViewImage->recordId, array('mainViewImageId' => '0'));
             break;
         default:
             $modelName = $fileModel;
     }
     $modelName = class_exists($modelName) ? $modelName : 'File';
     if ($modelName::model()->findByPk($id)->delete()) {
         if ($multipleImages == 'yes') {
             echo json_encode(array("result" => false));
         } else {
             echo json_encode(array("result" => true));
         }
     } else {
         echo json_encode(array("result" => false));
     }
 }
Example #22
0
 protected function getOldFile()
 {
     $oldFile = null;
     $formModel = $this->getFormModel();
     $attributes = array('id_object' => $formModel->objectId, 'id_instance' => $formModel->instanceId, 'id_parameter' => $formModel->parameterId, 'id_tmp' => $formModel->tmpId, 'id_parent_file' => null);
     if ($this->multiple === false) {
         $oldFile = File::model()->findByAttributes($attributes);
     } else {
         $fileName = $this->fileName;
         $oldFile = File::model()->findByAttributes($attributes, 'LOWER(RIGHT(file_path, ' . mb_strlen($fileName) . ')) = :FILE_NAME', array(':FILE_NAME' => mb_strtolower($fileName)));
     }
     return $oldFile;
 }
 /**
  * Returns the data model based on the primary key given in the GET variable.
  * If the data model is not found, an HTTP exception will be raised.
  * @param integer $id the ID of the model to be loaded
  * @return File the loaded model
  * @throws CHttpException
  */
 public function loadModel($id)
 {
     $model = File::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
Example #24
0
 protected function afterSave()
 {
     if ($this->isNewRecord) {
         $idObject = $this->id_object;
         $notChangeObject = array(20, 21);
         if (!in_array($idObject, $notChangeObject)) {
             $this->sqlChange($this, 'insert');
         }
     } else {
         $pk = $this->getPkBeforeSave();
         $idOldParameter = $pk['id_parameter'];
         if ($this->id_parameter != $idOldParameter) {
             DaObject::model()->updateAll(array('id_field_order' => $this->id_parameter), 'id_field_order=:param', array(':param' => $idOldParameter));
             DaObject::model()->updateAll(array('id_field_caption' => $this->id_parameter), 'id_field_caption=:param', array(':param' => $idOldParameter));
             File::model()->updateAll(array('id_parameter' => $this->id_parameter), 'id_parameter=:param', array(':param' => $idOldParameter));
             DaObjectViewColumn::model()->updateAll(array('id_object_parameter' => $this->id_parameter), 'id_object_parameter=:param', array(':param' => $idOldParameter));
         }
     }
     return parent::afterSave();
 }
Example #25
0
        <?php 
if (Yii::app()->user->isGuest) {
    ?>
        <?php 
    echo CHtml::link('Войти', '#', array('onclick' => '$("#login").dialog("open"); return false;'));
    ?>

        <?php 
} else {
    echo '<span>' . Yii::app()->user->name . ' | </span>';
    echo CHtml::link('Выйти', array('logout/logout'));
}
?>
        
        <?php 
foreach (File::model()->findAll() as $file) {
    ?>
        <?php 
    if (Yii::app()->user->isGuest) {
    } else {
        ?>
        <a href="<?php 
        echo Yii::app()->request->baseUrl;
        ?>
/uploads/1/<?php 
        echo $file->file;
        ?>
">Скачать прайс</a>
        <?php 
    }
    ?>
Example #26
0
 /**
  * Returns the data model based on the primary key given in the GET variable.
  * If the data model is not found, an HTTP exception will be raised.
  * @param integer $id the ID of the model to be loaded
  * @return Admin the loaded model
  * @throws CHttpException
  */
 public function loadModel($id)
 {
     $model = File::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404);
     }
     return $model;
 }
Example #27
0
 public function actionDownloadCount()
 {
     if (isset($_POST['file_href'])) {
         $file = File::model()->findByAttributes(array('location' => $_POST['file_href']));
         $file->download_count += 1;
         if (!$file->saveAttributes(array('download_count' => $file->download_count))) {
             Util::returnJSON(array("success" => false, "message" => Yii::t("app", "Add Count Error.")));
         }
         Util::returnJSON(array("success" => true));
     }
 }
Example #28
0
 protected function afterSave()
 {
     parent::afterSave();
     if ($this->isNewRecord) {
         $idObject = $this->id_object;
         if ($this->object_type == self::OBJECT_TYPE_TABLE && $this->table_name != "") {
             // Если создается объект у которого тип=Таблица, то создаем свойство Первичного ключа
             $p = ObjectParameter::newModel('ObjectParameter');
             $p->id_object = $idObject;
             $p->id_parameter_type = DataType::PRIMARY_KEY;
             $p->caption = 'id';
             $fieldName = 'id_' . str_replace(array('da_', 'pr_'), '', $this->table_name);
             $p->field_name = $fieldName;
             $p->id_parameter = $idObject . '-' . str_replace('_', '-', $fieldName);
             $p->setIsRequired(true);
             $p->save();
         }
     } else {
         if ($this->id_object != $this->getPkBeforeSave()) {
             ObjectParameter::model()->updateAll(array('id_object' => $this->id_object), 'id_object=:obj', array(':obj' => $this->getPkBeforeSave()));
             ObjectParameter::model()->updateAll(array('add_parameter' => $this->id_object), 'id_parameter_type=7 AND add_parameter=:obj', array(':obj' => $this->getPkBeforeSave()));
             DaObjectView::model()->updateAll(array('id_object' => $this->id_object), 'id_object=:obj', array(':obj' => $this->getPkBeforeSave()));
             DaObjectViewColumn::model()->updateAll(array('id_object' => $this->id_object), 'id_object=:obj', array(':obj' => $this->getPkBeforeSave()));
             File::model()->updateAll(array('id_object' => $this->id_object), 'id_object=:obj', array(':obj' => $this->getPkBeforeSave()));
             Search::model()->updateAll(array('id_object' => $this->id_object), 'id_object=:obj', array(':obj' => $this->getPkBeforeSave()));
         }
     }
 }
Example #29
0
 /**
  * 批量清理指定天数之前的备份
  * @param $days		int		有效期的天数,默认30(之前的都会被清理掉)
  * @return 清理结果 true
  */
 protected function cleanFile($days = 30)
 {
     $criteria = new EMongoCriteria();
     $criteria->addCond('metadata.addTime', '<', time() - $days * 24 * 3600);
     //指明对象
     return File::model()->deleteAll($criteria);
 }
Example #30
0
 private function getFullFileResultByKeyword($fileIds)
 {
     $temp_file_criteria = new CDbCriteria();
     $temp_file_criteria->addInCondition("id", $fileIds);
     return File::model()->findAll($temp_file_criteria);
 }