1
0
Fork 0
mirror of https://github.com/Oreolek/ifhub.club.git synced 2024-06-26 03:30:48 +03:00

Дополнительные поля: функционал загрузки файлов для поля с типом "file"

This commit is contained in:
Mzhelskiy Maxim 2014-04-02 19:21:58 +07:00
parent 90450b7f5b
commit c527f9dc23
7 changed files with 161 additions and 8 deletions

View file

@ -0,0 +1,104 @@
<?php
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Экшен обработки УРЛа вида /property/
*
* @package actions
* @since 1.0
*/
class ActionProperty extends Action {
/**
* Текущий пользователь
*
* @var ModuleUser_EntityUser|null
*/
protected $oUserCurrent=null;
/**
* Инициализация
*/
public function Init() {
/**
* Достаём текущего пользователя
*/
$this->oUserCurrent=$this->User_GetUserCurrent();
}
/**
* Регистрируем евенты
*/
protected function RegisterEvent() {
$this->AddEventPreg('/^download$/i','/^[\w]{10,32}$/i','/^$/i','EventDownloadFile');
}
/**********************************************************************************
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
**********************************************************************************
*/
/**
* Загрузка файла
*/
protected function EventDownloadFile() {
$sKey=$this->GetParam(0);
/**
* Выполняем проверки
*/
if (!$oValue=$this->Property_GetValueByValueVarchar($sKey)) {
return parent::EventNotFound();
}
if (!$oProperty=$oValue->getProperty()) {
return parent::EventNotFound();
}
if ($oProperty->getType()!=ModuleProperty::PROPERTY_TYPE_FILE) {
return parent::EventNotFound();
}
if (!$oTargetRel=$this->Property_GetTargetByType($oValue->getTargetType())) {
return parent::EventNotFound();
}
if ($oTargetRel->getState()!=ModuleProperty::TARGET_STATE_ACTIVE) {
return parent::EventNotFound();
}
$bAllowDownload=false;
if (!$this->oUserCurrent) {
if ($oProperty->getParam('access_only_auth')) {
return Router::Action('error','403');
} else {
$bAllowDownload=true;
}
}
if (!$bAllowDownload) {
/**
* Проверяем доступ пользователя к объекту, которому принадлежит свойство
*/
if ($this->Property_CheckAllowTargetObject($oValue->getTargetType(),$oValue->getTargetId(),array('user'=>$this->oUserCurrent))) {
$bAllowDownload=true;
}
}
if ($bAllowDownload) {
$oValueType=$oValue->getValueTypeObject();
if (!$oValueType->DownloadFile()) {
return parent::EventNotFound();
}
} else {
return Router::Action('error','403');
}
$this->SetTemplate(false);
}
}

View file

@ -781,4 +781,18 @@ class ModuleProperty extends ModuleORM {
return $bRes;
}
public function CheckAllowTargetObject($sTargetType,$iTargetId,$aParams=array()) {
$sMethod = 'CheckAllowTargetObject'.func_camelize($sTargetType);
if (method_exists($this,$sMethod)) {
if (!array_key_exists('user',$aParams)) {
$aParams['user']=$this->oUserCurrent;
}
return $this->$sMethod($iTargetId,$aParams);
}
/**
* По умолчанию считаем доступ разрешен
*/
return true;
}
}

View file

@ -22,7 +22,7 @@
class ModuleProperty_EntityValue extends EntityORM {
protected $aRelations=array(
'property' => array(self::RELATION_TYPE_BELONGS_TO,'ModuleProperty_EntityProperty','property_id'),
);
protected function beforeSave() {

View file

@ -22,8 +22,7 @@
class ModuleProperty_EntityValueTypeFile extends ModuleProperty_EntityValueType {
public function getValueForDisplay() {
$oValue=$this->getValueObject();
return $oValue->getValueVarchar();
return $this->getFileFullName();
}
public function validate() {
@ -170,7 +169,10 @@ class ModuleProperty_EntityValueTypeFile extends ModuleProperty_EntityValueType
'name'=>htmlspecialchars($aPathInfo['filename']),
'extension'=>htmlspecialchars($aPathInfo['extension']),
));
$oValue->setValueVarchar(htmlspecialchars($aPathInfo['filename'].'.'.$aPathInfo['extension']));
/**
* Сохраняем уникальный ключ для доступа к файлу
*/
$oValue->setValueVarchar(func_generator(32));
}
}
}
@ -220,6 +222,14 @@ class ModuleProperty_EntityValueTypeFile extends ModuleProperty_EntityValueType
}
}
public function getFileFullName() {
$oValue=$this->getValueObject();
if ($aFilePrev=$oValue->getDataOne('file')) {
return $aFilePrev['name'].'.'.$aFilePrev['extension'];
}
return null;
}
/**
* Сохраняет(копирует) файл на сервер
* Если переопределить данный метод, то можно сохранять файл, например, на Amazon S3
@ -248,4 +258,12 @@ class ModuleProperty_EntityValueTypeFile extends ModuleProperty_EntityValueType
$sPathFile=$this->Fs_GetPathServer($sPathFile);
return $this->Fs_RemoveFileLocal($sPathFile);
}
public function DownloadFile() {
$oValue=$this->getValueObject();
if ($aFilePrev=$oValue->getDataOne('file')) {
$this->Tools_DownloadFile($this->Fs_GetPathServer($aFilePrev['path']),$aFilePrev['name'].'.'.$aFilePrev['extension'],$aFilePrev['size']);
}
return false;
}
}

View file

@ -90,11 +90,27 @@ class ModuleTools extends Module {
public function CallbackParserTagLs($sTag,$aParams) {
$sText='';
if (isset($aParams['user'])) {
if ($oUser=$this->User_getUserByLogin($aParams['user'])) {
if ($oUser=$this->User_GetUserByLogin($aParams['user'])) {
$sText.="<a href=\"{$oUser->getUserWebPath()}\" class=\"ls-user\">{$oUser->getLogin()}</a> ";
}
}
return $sText;
}
}
?>
public function DownloadFile($sFilePath,$sFileName,$iFileSize=null) {
if (file_exists($sFilePath) and $file=fopen($sFilePath,"r")) {
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".urlencode($sFileName).";");
header("Content-Transfer-Encoding: binary");
if ($iFileSize) {
header("Content-Length: ".$iFileSize);
}
while (!feof($file)) {
$sContent=fread($file ,1024*100);
echo $sContent;
}
exit(0);
}
return false;
}
}

View file

@ -336,6 +336,7 @@ $config['router']['page']['feed'] = 'ActionUserfeed';
$config['router']['page']['stream'] = 'ActionStream';
$config['router']['page']['subscribe'] = 'ActionSubscribe';
$config['router']['page']['content'] = 'ActionContent';
$config['router']['page']['property'] = 'ActionProperty';
// Глобальные настройки роутинга
$config['router']['config']['action_default'] = 'index';
$config['router']['config']['action_not_found'] = 'error';

View file

@ -2,7 +2,7 @@
<div class="property-list-item">
<div class="property-list-item-label">{$oPropertyItem->getTitle()}</div>
{if $oUserCurrent or !$oPropertyItem->getParam('access_only_auth')}
<a href="{router page="property/download"}{$oValue->getId()}/">{$oValue->getValueForDisplay()}</a>
<a href="{router page="property/download"}{$oValue->getValueVarchar()}/">{$oValue->getValueForDisplay()}</a>
{else}
Для доступа к файлу <a href="#" class="js-modal-toggle-login">необходимо авторизоваться</a>
{/if}