mirror of
https://github.com/Oreolek/ifhub.club.git
synced 2024-06-16 23:00:51 +03:00
Доработка медиа файлов - загрузка/вставка изображения по ссылке
This commit is contained in:
parent
00d46b8b83
commit
a8c02ffdc3
|
@ -82,6 +82,7 @@ class ActionAjax extends Action {
|
|||
$this->AddEventPreg('/^infobox$/i','/^info$/','/^blog$/','EventInfoboxInfoBlog');
|
||||
|
||||
$this->AddEventPreg('/^media$/i','/^upload$/','/^$/','EventMediaUpload');
|
||||
$this->AddEventPreg('/^media$/i','/^upload-link$/','/^$/','EventMediaUploadLink');
|
||||
$this->AddEventPreg('/^media$/i','/^generate-target-tmp$/','/^$/','EventMediaGenerateTargetTmp');
|
||||
$this->AddEventPreg('/^media$/i','/^submit-insert$/','/^$/','EventMediaSubmitInsert');
|
||||
$this->AddEventPreg('/^media$/i','/^submit-create-photoset$/','/^$/','EventMediaSubmitCreatePhotoset');
|
||||
|
@ -96,6 +97,57 @@ class ActionAjax extends Action {
|
|||
**********************************************************************************
|
||||
*/
|
||||
|
||||
|
||||
protected function EventMediaUploadLink() {
|
||||
/**
|
||||
* Пользователь авторизован?
|
||||
*/
|
||||
if (!$this->oUserCurrent) {
|
||||
$this->Message_AddErrorSingle($this->Lang_Get('need_authorization'),$this->Lang_Get('error'));
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* URL передали?
|
||||
*/
|
||||
if (!($sUrl=getRequestStr('url'))) {
|
||||
$this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Проверяем корректность target'а
|
||||
*/
|
||||
$sTargetType=getRequestStr('target_type');
|
||||
$sTargetId=getRequestStr('target_id');
|
||||
|
||||
$sTargetTmp=empty($_COOKIE['media_target_tmp_'.$sTargetType]) ? getRequestStr('target_tmp') : $_COOKIE['media_target_tmp_'.$sTargetType];
|
||||
if ($sTargetId) {
|
||||
$sTargetTmp=null;
|
||||
if (!$this->Media_CheckTarget($sTargetType,$sTargetId)) {
|
||||
$this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
$sTargetId=null;
|
||||
if (!$sTargetTmp or !$this->Media_IsAllowTargetType($sTargetType)) {
|
||||
$this->Message_AddError($this->Lang_Get('system_error'), $this->Lang_Get('error'));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Выполняем загрузку файла
|
||||
*/
|
||||
if ($mResult=$this->Media_UploadUrl($sUrl,$sTargetType,$sTargetId,$sTargetTmp) and is_object($mResult)) {
|
||||
$aParams=array(
|
||||
'align'=>getRequestStr('align'),
|
||||
'title'=>getRequestStr('title')
|
||||
);
|
||||
$this->Viewer_AssignAjax('sText',$this->Media_BuildCodeForEditor($mResult,$aParams));
|
||||
} else {
|
||||
$this->Message_AddError(is_string($mResult) ? $mResult : $this->Lang_Get('system_error'), $this->Lang_Get('error'));
|
||||
}
|
||||
}
|
||||
|
||||
protected function EventMediaSaveDataFile() {
|
||||
/**
|
||||
* Пользователь авторизован?
|
||||
|
|
|
@ -168,9 +168,51 @@ class ModuleMedia extends ModuleORM {
|
|||
|
||||
public function UploadUrl($sFileUrl,$sTargetType,$sTargetId,$sTargetTmp=null) {
|
||||
/**
|
||||
* TODO: сделать загрузку по урлу
|
||||
* Проверяем, является ли файл изображением
|
||||
* TODO: файл может быть не только изображением, поэтому требуется рефакторинг
|
||||
*/
|
||||
return false;
|
||||
if(!$aImageInfo=(@getimagesize($sFileUrl))) {
|
||||
return 'Файл не является изображением';
|
||||
}
|
||||
$aTypeImage=array(1=>'gif',2=>'jpg',3=>'png'); // see http://php.net/manual/en/function.exif-imagetype.php
|
||||
$sExtension=isset($aTypeImage[$aImageInfo[2]]) ? $aTypeImage[$aImageInfo[2]] : 'jpg';
|
||||
/**
|
||||
* Открываем файловый поток и считываем файл поблочно,
|
||||
* контролируя максимальный размер изображения
|
||||
*/
|
||||
$rFile=fopen($sFileUrl,'r');
|
||||
if(!$rFile) {
|
||||
return 'Не удалось загрузить файл';
|
||||
}
|
||||
|
||||
$iMaxSizeKb=Config::Get('module.media.image_max_size_url');
|
||||
$iSizeKb=0;
|
||||
$sContent='';
|
||||
while (!feof($rFile) and $iSizeKb<$iMaxSizeKb) {
|
||||
$sContent.=fread($rFile ,1024*2);
|
||||
$iSizeKb++;
|
||||
}
|
||||
/**
|
||||
* Если конец файла не достигнут,
|
||||
* значит файл имеет недопустимый размер
|
||||
*/
|
||||
if(!feof($rFile)) {
|
||||
return 'Превышен максимальный размер файла: '.Config::Get('module.media.image_max_size_url').'Kb';
|
||||
}
|
||||
fclose($rFile);
|
||||
/**
|
||||
* Копируем загруженный файл
|
||||
*/
|
||||
$sDirTmp=Config::Get('path.tmp.server').'/media/';
|
||||
if (!is_dir($sDirTmp)) {
|
||||
@mkdir($sDirTmp,0777,true);
|
||||
}
|
||||
$sFileTmp=$sDirTmp.func_generator().'.'.$sExtension;
|
||||
$rFile=fopen($sFileTmp,'w');
|
||||
fwrite($rFile,$sContent);
|
||||
fclose($rFile);
|
||||
|
||||
return $this->ProcessingFile($sFileTmp,$sTargetType,$sTargetId,$sTargetTmp);
|
||||
}
|
||||
|
||||
public function ProcessingFile($sFileTmp,$sTargetType,$sTargetId,$sTargetTmp=null) {
|
||||
|
@ -178,7 +220,7 @@ class ModuleMedia extends ModuleORM {
|
|||
* Определяем тип файла по расширенияю и запускаем обработку
|
||||
*/
|
||||
$aPathInfo=pathinfo($sFileTmp);
|
||||
$sExtension=strtolower($aPathInfo['extension']);
|
||||
$sExtension=@strtolower($aPathInfo['extension']);
|
||||
if (in_array($sExtension,array('jpg','jpeg','gif','png'))) {
|
||||
return $this->ProcessingFileImage($sFileTmp,$sTargetType,$sTargetId,$sTargetTmp);
|
||||
}
|
||||
|
@ -318,9 +360,12 @@ class ModuleMedia extends ModuleORM {
|
|||
$sPath=$oMedia->getFileWebPath($sSize=='original' ? null : $sSize);
|
||||
|
||||
$sCode='<img src="'.$sPath.'" ';
|
||||
if (!isset($aParams['skip_title']) and $oMedia->getDataOne('title')) {
|
||||
$sCode.=' title="'.htmlspecialchars($oMedia->getDataOne('title')).'" ';
|
||||
$sCode.=' alt="'.htmlspecialchars($oMedia->getDataOne('title')).'" ';
|
||||
if (!isset($aParams['title'])) {
|
||||
$aParams['title']=$oMedia->getDataOne('title');
|
||||
}
|
||||
if (!isset($aParams['skip_title']) and $aParams['title']) {
|
||||
$sCode.=' title="'.htmlspecialchars($aParams['title']).'" ';
|
||||
$sCode.=' alt="'.htmlspecialchars($aParams['title']).'" ';
|
||||
}
|
||||
if (isset($aParams['align']) and in_array($aParams['align'],array('left','right','center'))) {
|
||||
if ($aParams['align'] == 'center') {
|
||||
|
|
|
@ -233,6 +233,7 @@ $config['module']['topic']['photoset']['size'] = array( // спис
|
|||
*/
|
||||
$config['module']['media']['image_max_width'] = 5000; // Максимальный размер изображения по ширине
|
||||
$config['module']['media']['image_max_height'] = 5000; // Максимальный размер изображения по высоте
|
||||
$config['module']['media']['image_max_size_url'] = 1024; // Максимальный размер изображения в kB для загрузки по URL
|
||||
$config['module']['media']['image_sizes'] = array( // список размеров, которые необходимо делать при загрузке изображения
|
||||
array(
|
||||
'w' => 1000,
|
||||
|
|
|
@ -35,6 +35,14 @@ ls.media = (function ($) {
|
|||
file_list: '.js-media-upload-gallery-list',
|
||||
file: '.js-media-upload-gallery-item'
|
||||
},
|
||||
link: {
|
||||
form: '.js-media-link-form',
|
||||
url: 'input[name=url]',
|
||||
title: 'input[name=title]',
|
||||
align: 'select[name=align]',
|
||||
insertButton: '.js-media-link-insert-button',
|
||||
uploadButton: '.js-media-link-upload-button'
|
||||
},
|
||||
info: {
|
||||
sizes: 'select[name=size]',
|
||||
empty: '.js-media-item-info-empty'
|
||||
|
@ -60,7 +68,8 @@ ls.media = (function ($) {
|
|||
generate_target_tmp: aRouter['ajax'] + "media/generate-target-tmp/",
|
||||
submit_insert: aRouter['ajax'] + "media/submit-insert/",
|
||||
submit_photoset: aRouter['ajax'] + "media/submit-create-photoset/",
|
||||
save_data_file: aRouter['ajax'] + "media/save-data-file/"
|
||||
save_data_file: aRouter['ajax'] + "media/save-data-file/",
|
||||
upload_link: aRouter['ajax'] + "media/upload-link/"
|
||||
},
|
||||
// HTML
|
||||
html: {
|
||||
|
@ -69,6 +78,8 @@ ls.media = (function ($) {
|
|||
};
|
||||
|
||||
this.mode = 'insert';
|
||||
this._countCheckLink=0;
|
||||
this._blockCheckLink=-1;
|
||||
|
||||
/**
|
||||
* Инициализация
|
||||
|
@ -86,6 +97,13 @@ ls.media = (function ($) {
|
|||
gallery: {
|
||||
fileList: $(this.options.selectors.gallery.file_list)
|
||||
},
|
||||
link: {
|
||||
url: $(this.options.selectors.link.form).find(this.options.selectors.link.url),
|
||||
align: $(this.options.selectors.link.form).find(this.options.selectors.link.align),
|
||||
title: $(this.options.selectors.link.form).find(this.options.selectors.link.title),
|
||||
insertButton: $(this.options.selectors.link.insertButton),
|
||||
uploadButton: $(this.options.selectors.link.uploadButton)
|
||||
},
|
||||
info: {
|
||||
sizes: $(this.options.selectors.info.sizes),
|
||||
empty: $(this.options.selectors.info.empty)
|
||||
|
@ -100,6 +118,7 @@ ls.media = (function ($) {
|
|||
}
|
||||
|
||||
this.elements.buttonsInsert.prop('disabled', true);
|
||||
this.elements.link.uploadButton.prop('disabled', true);
|
||||
this.elements.info.empty.show();
|
||||
|
||||
// Настройки загрузчика
|
||||
|
@ -163,17 +182,113 @@ ls.media = (function ($) {
|
|||
this.saveDataFile($(e.currentTarget).attr('name'),$(e.currentTarget).val());
|
||||
}.bind(this));
|
||||
|
||||
// инициализация фоторамы при предпросмотре
|
||||
// Инициализация фоторамы при предпросмотре
|
||||
ls.hook.add('ls_topic_preview_after',function(){
|
||||
$('.fotorama').fotorama();
|
||||
});
|
||||
|
||||
// Проверка корректности урла при вставке ссылки на медиа-объект
|
||||
this.elements.link.url.on('input',function(){
|
||||
this.checkLinkUrl(this.elements.link.url.val());
|
||||
}.bind(this));
|
||||
|
||||
// Вставка медиа ссылки в текст
|
||||
this.elements.link.insertButton.on('click',function(){
|
||||
var sTitle=this.elements.link.title.val();
|
||||
var sTextInsert;
|
||||
|
||||
if ($('.js-media-link-settings-image').is(':visible')) {
|
||||
var sAlign=this.elements.link.align.val();
|
||||
sAlign = sAlign == 'center' ? 'class="image-center"' : 'align="' + sAlign + '"';
|
||||
sTextInsert='<img src="' + this.elements.link.url.val() + '" title="' + sTitle + '" ' + sAlign + ' />';
|
||||
} else {
|
||||
sTextInsert='<a href="'+this.elements.link.url.val()+'">'+sTitle+'</a>';
|
||||
}
|
||||
|
||||
this.insertTextToEditor(sTextInsert);
|
||||
this.elements.modal.modal('hide');
|
||||
}.bind(this));
|
||||
|
||||
// Загрузка медиа файлы по ссылке
|
||||
this.elements.link.uploadButton.on('click',function(){
|
||||
ls.ajax.submit(this.options.routers.upload_link, $('.js-media-link-form'), function (data){
|
||||
if (data.bStateError) {
|
||||
ls.msg.error(data.sMsgTitle,data.sMsg);
|
||||
} else {
|
||||
this.insertTextToEditor(data.sText);
|
||||
this.elements.modal.modal('hide');
|
||||
this.loadImageList(); // обновляем список файлов
|
||||
}
|
||||
}.bind(this), {
|
||||
// TODO: Fix validation
|
||||
validate: false,
|
||||
submitButton: this.elements.link.uploadButton,
|
||||
params: { target_type: this.options.target_type, target_id: this.options.target_id, target_tmp: this.options.target_tmp }
|
||||
});
|
||||
}.bind(this));
|
||||
|
||||
this.loadImageList();
|
||||
this.bindFileEvents();
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* Проверка корректности ссылки на медиа
|
||||
*
|
||||
* @param url
|
||||
*/
|
||||
this.checkLinkUrl = function(url) {
|
||||
// TODO: здесь нужно показывать спинер загрузки в инпуте
|
||||
|
||||
this._countCheckLink++;
|
||||
this.checkLinkUrlImage(url,function(src,result){
|
||||
if (!result) {
|
||||
// если не изображение, то проверяем на другой тип, например, видео
|
||||
|
||||
// разрешаем скрытие настроек только след итерациям после успешной проверки
|
||||
if (this._blockCheckLink<this._countCheckLink) {
|
||||
this.hideSettingsLinkImage();
|
||||
}
|
||||
} else {
|
||||
this._blockCheckLink=this._countCheckLink;
|
||||
this.showSettingsLinkImage(src);
|
||||
}
|
||||
}.bind(this));
|
||||
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Проверка на корректность ссылки на изображение
|
||||
*
|
||||
* @param url
|
||||
* @param callback
|
||||
*/
|
||||
this.checkLinkUrlImage = function(url,callback) {
|
||||
$this=this;
|
||||
$('<img>',{
|
||||
src: url,
|
||||
error: function() {
|
||||
callback.call($this,this.src,false);
|
||||
},
|
||||
load: function() {
|
||||
callback.call($this,this.src,true);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
this.showSettingsLinkImage = function(src) {
|
||||
this.elements.link.uploadButton.prop('disabled', false);
|
||||
$('.js-media-link-settings-image-preview').attr('src',src);
|
||||
$('.js-media-link-settings-image').show();
|
||||
};
|
||||
|
||||
this.hideSettingsLinkImage = function() {
|
||||
this.elements.link.uploadButton.prop('disabled', true);
|
||||
$('.js-media-link-settings-image').hide();
|
||||
};
|
||||
|
||||
/**
|
||||
* Устанавливает текущий режим вставки медиа файлов
|
||||
*/
|
||||
this.setMode = function(mode) {
|
||||
this.mode = mode;
|
||||
|
@ -205,7 +320,7 @@ ls.media = (function ($) {
|
|||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* Скрывает форму с настройками
|
||||
*/
|
||||
this.hideSettingsMode = function() {
|
||||
$('.js-media-settings-mode').hide();
|
||||
|
@ -454,13 +569,17 @@ ls.media = (function ($) {
|
|||
if (result.bStateError) {
|
||||
ls.msg.error(result.sMsgTitle,result.sMsg);
|
||||
} else {
|
||||
$.markItUp({
|
||||
replaceWith: result.sTextResult
|
||||
});
|
||||
this.insertTextToEditor(result.sTextResult);
|
||||
this.elements.modal.modal('hide');
|
||||
}
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
this.insertTextToEditor = function(text) {
|
||||
$.markItUp({
|
||||
replaceWith: text
|
||||
});
|
||||
};
|
||||
|
||||
return this;
|
||||
}).call(ls.media || {},jQuery);
|
|
@ -28,7 +28,7 @@
|
|||
<ul class="modal-upload-image-nav" data-type="tabs">
|
||||
<li data-type="tab" data-tab-target="tab-media-insert" data-media-mode="insert" class="active js-tab-show-gallery"><a href="#">Вставить</a></li>
|
||||
<li data-type="tab" data-tab-target="tab-media-create-photoset" data-media-mode="create-photoset" class="js-tab-show-gallery"><a href="#">Создать фотосет</a></li>
|
||||
<!--<li data-type="tab" data-tab-target="tab-media-link"><a href="#">{$aLang.uploadimg_from_link}</a></li>-->
|
||||
<li data-type="tab" data-tab-target="tab-media-link"><a href="#">Вставить по ссылке</a></li>
|
||||
</ul>
|
||||
|
||||
{* Side navigation content *}
|
||||
|
@ -51,28 +51,42 @@
|
|||
{**
|
||||
* Ссылка
|
||||
*}
|
||||
<form method="POST" action="" enctype="multipart/form-data" id="tab-media-link" onsubmit="return false;" data-type="tab-pane" class="tab-pane modal-upload-image-pane">
|
||||
<form method="POST" action="" enctype="multipart/form-data" id="tab-media-link" onsubmit="return false;" data-type="tab-pane" class="tab-pane modal-upload-image-pane js-media-link-form">
|
||||
<div class="modal-content">
|
||||
<p><label for="img_url">{$aLang.uploadimg_url}:</label>
|
||||
<input type="text" name="img_url" id="img_url" value="http://" class="width-full" /></p>
|
||||
|
||||
<p>
|
||||
<label for="form-image-url-align">{$aLang.uploadimg_align}:</label>
|
||||
<select name="align" id="form-image-url-align" class="width-full">
|
||||
<option value="">{$aLang.uploadimg_align_no}</option>
|
||||
<option value="left">{$aLang.uploadimg_align_left}</option>
|
||||
<option value="right">{$aLang.uploadimg_align_right}</option>
|
||||
<option value="center">{$aLang.uploadimg_align_center}</option>
|
||||
</select>
|
||||
<input type="text" name="url" value="http://" class="width-full" />
|
||||
</p>
|
||||
|
||||
<p><label for="form-image-url-title">{$aLang.uploadimg_title}:</label>
|
||||
<input type="text" name="title" id="form-image-url-title" value="" class="width-full" /></p>
|
||||
<p>
|
||||
<label>
|
||||
{$aLang.uploadimg_title}:
|
||||
<input type="text" name="title" value="" class="width-full" />
|
||||
</label>
|
||||
</p>
|
||||
|
||||
<div style="display: none;" class="js-media-link-settings-image">
|
||||
<p>
|
||||
<img src="" width="200" class="js-media-link-settings-image-preview">
|
||||
</p>
|
||||
<p>
|
||||
<label>
|
||||
{$aLang.uploadimg_align}:
|
||||
<select name="align" class="width-full">
|
||||
<option value="">{$aLang.uploadimg_align_no}</option>
|
||||
<option value="left">{$aLang.uploadimg_align_left}</option>
|
||||
<option value="right">{$aLang.uploadimg_align_right}</option>
|
||||
<option value="center">{$aLang.uploadimg_align_center}</option>
|
||||
</select>
|
||||
</label>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
<div class="modal-footer">
|
||||
<button type="submit" class="button button-primary js-insert-image-button">Вставить</button>
|
||||
<button type="submit" class="button button-primary js-upload-image-button" data-form-id="tab-upload-link">{$aLang.uploadimg_link_submit_load}</button>
|
||||
<button type="submit" class="button button-primary js-media-link-insert-button">Вставить как ссылку</button>
|
||||
<button type="submit" class="button button-primary js-media-link-upload-button">Загрузить и вставить</button>
|
||||
<button type="button" class="button" data-type="modal-close">{$aLang.uploadimg_cancel}</button>
|
||||
</div>
|
||||
</form>
|
||||
|
|
Loading…
Reference in a new issue