瀏覽代碼

Ticket #3612- Timeline: Allow to insert images with Ctrl+v and use custom uploader.

AntonLV 4 年之前
父節點
當前提交
b1bee6cf57

+ 2 - 0
modules/boonex/russian/data/langs/bx_timeline/ru.xml

@@ -50,6 +50,7 @@
     <string name="_bx_timeline_option_cache_item_engine"><![CDATA[Механизм кэширования элемента (отличный от FileHtml может потребовать дополнительную настройку сервера)]]></string>
     <string name="_bx_timeline_option_cache_item_lifetime"><![CDATA[Время жизни кэша элемента]]></string>
     <string name="_bx_timeline_option_enable_editor_toolbar"><![CDATA[Включить панель инструментов в форме создания сообщения]]></string>
+    <string name="_bx_timeline_option_editor_auto_attach_insertion"><![CDATA[Обрабатывать изображения, вставленные в редактор, как вложения]]></string>
     <string name="_bx_timeline_option_limit_attach_links"><![CDATA[Ограничить число присоединенных линок (0 - без ограничений)]]></string>
 
     <string name="_bx_timeline_form_post"><![CDATA[Сообщение]]></string>
@@ -304,6 +305,7 @@
     <string name="_bx_timeline_txt_msg_no_results"><![CDATA[Пусто]]></string>
     <string name="_bx_timeline_txt_msg_performed_action"><![CDATA[Действие было успешно выполнено.]]></string>
     <string name="_bx_timeline_txt_msg_posted"><![CDATA[Успешно опубликовано.]]></string>
+    <string name="_bx_timeline_txt_err_cannot_perform_insertion"><![CDATA[Невозможно выполнить вставку.]]></string>
     <string name="_bx_timeline_txt_err_cannot_perform_action"><![CDATA[Невозможно выполнить действие. Пожалуйста, оповестите нас об этой проблеме.]]></string>
     <string name="_bx_timeline_txt_err_empty_post"><![CDATA[Сообщение пусто.]]></string>
     <string name="_bx_timeline_txt_err_attach_links"><![CDATA[Достигнуто максимально допустимое количество прикрепленных ссылок.]]></string>

+ 7 - 0
modules/boonex/timeline/classes/BxTimelineConfig.php

@@ -51,6 +51,7 @@ class BxTimelineConfig extends BxBaseModNotificationsConfig
     protected $_aHotList;
 
     protected $_bEditorToolbar;
+    protected $_bEditorAutoAttach;
     protected $_iLimitAttachLinks;
 
     protected $_bUnhideRestored;
@@ -404,6 +405,7 @@ class BxTimelineConfig extends BxBaseModNotificationsConfig
         $this->_aHotList = $this->_bHot ? $this->_oDb->getHot() : array();
 
         $this->_bEditorToolbar = getParam($sOptionPrefix . 'enable_editor_toolbar') == 'on';
+        $this->_bEditorAutoAttach = getParam($sOptionPrefix . 'editor_auto_attach_insertion') == 'on';
         $this->_iLimitAttachLinks = (int)getParam($sOptionPrefix . 'limit_attach_links');
 
         $this->_bUnhideRestored = false;
@@ -546,6 +548,11 @@ class BxTimelineConfig extends BxBaseModNotificationsConfig
     	return $this->_bEditorToolbar;
     }
 
+    public function isEditorAutoAttach()
+    {
+    	return $this->_bEditorAutoAttach;
+    }
+
     public function isUnhideRestored()
     {
         return $this->_bUnhideRestored;

+ 16 - 3
modules/boonex/timeline/classes/BxTimelineFormPost.php

@@ -39,7 +39,17 @@ class BxTimelineFormPost extends BxBaseModGeneralFormEntry
         $this->_aUploadersInfo = array();
     }
 
-    function initChecker($aValues = array (), $aSpecificValues = array())
+    public function getUploadersInfo($sField = '')
+    {
+        if(empty($sField))
+            return $this->_aUploadersInfo;
+
+        $aUploaders = !empty($this->aInputs[$sField]['value']) ? unserialize($this->aInputs[$sField]['value']) : $this->_oModule->_oConfig->getUploaders($sField);
+
+        return $this->_aUploadersInfo[array_shift($aUploaders)];
+    }
+
+    public function initChecker($aValues = array (), $aSpecificValues = array())
     {
         $CNF = &$this->_oModule->_oConfig->CNF;
         
@@ -187,6 +197,7 @@ class BxTimelineFormPost extends BxBaseModGeneralFormEntry
             foreach($aUploaders as $sUploader)
                 $this->_aUploadersInfo[$sUploader] = array(
                     'id' => $sUploadersId, 
+                    'name' => $sUploader,
                     'js_object' => BxDolUploader::getObjectInstance($sUploader, $sStorage, $sUploadersId)->getNameJsInstanceUploader()
                 );
 
@@ -207,7 +218,8 @@ class BxTimelineFormPost extends BxBaseModGeneralFormEntry
 
             foreach($aUploaders as $sUploader)
                 $this->_aUploadersInfo[$sUploader] = array(
-                    'id' => $sUploadersId, 
+                    'id' => $sUploadersId,
+                    'name' => $sUploader,
                     'js_object' => BxDolUploader::getObjectInstance($sUploader, $sStorage, $sUploadersId)->getNameJsInstanceUploader()
                 );
 
@@ -228,7 +240,8 @@ class BxTimelineFormPost extends BxBaseModGeneralFormEntry
           
             foreach($aUploaders as $sUploader){
                 $this->_aUploadersInfo[$sUploader] = array(
-                    'id' => $sUploadersId, 
+                    'id' => $sUploadersId,
+                    'name' => $sUploader,
                     'js_object' => BxDolUploader::getObjectInstance($sUploader, $sStorage, $sUploadersId)->getNameJsInstanceUploader()
                 );
             }

+ 28 - 1
modules/boonex/timeline/classes/BxTimelineModule.php

@@ -594,6 +594,29 @@ class BxTimelineModule extends BxBaseModNotificationsModule implements iBxDolCon
         echoJson($this->getFormAttachLink());
     }
 
+    public function actionAutoAttachInsertion()
+    {
+        $sTxtError = _t('_bx_timeline_txt_err_cannot_perform_insertion');
+
+        $sUploader = bx_process_input(bx_get('u'));
+        $sResultContainerId = bx_process_input(bx_get('uid'));
+
+        $sStorage = $this->_oConfig->getObject('storage_photos');
+        $oUploader = BxDolUploader::getObjectInstance($sUploader, $sStorage, $sResultContainerId, $this->_oTemplate);
+        if(!$oUploader)
+            return echoJson(['code' => 1, 'msg' => $sTxtError]);
+
+        ob_start();
+        $oUploader->handleUploads(bx_get_logged_profile_id(), isset($_FILES['file']) ? $_FILES['file'] : null, false, false, false);
+        ob_end_clean();
+
+        $sError = $oUploader->getUploadErrorMessages();
+        if(!empty($sError))
+            return echoJson(['code' => 2, 'msg' => $sError]);
+
+        return echoJson(['code' => 0, 'eval' => $oUploader->getNameJsInstanceUploader() . '.restoreGhosts()']);
+    }
+
     public function actionGetRepostedBy()
     {
         $iRepostedId = bx_process_input(bx_get('id'), BX_DATA_INT);
@@ -3168,7 +3191,11 @@ class BxTimelineModule extends BxBaseModNotificationsModule implements iBxDolCon
             return $this->_prepareResponse(array('message' => _t('_bx_timeline_txt_err_cannot_perform_action')), $bAjaxMode);
         }
 
-        return $this->_prepareResponse(array('form' => $oForm->getCode($bDynamicMode), 'form_id' => $oForm->id), $bAjaxMode && $oForm->isSubmitted());
+        $mixedResult = $this->_prepareResponse(array('form' => $oForm->getCode($bDynamicMode), 'form_id' => $oForm->id), $bAjaxMode && $oForm->isSubmitted());
+        if(is_array($mixedResult))
+            $mixedResult['form_object'] = $oForm;
+
+        return $mixedResult;
     }
 
     public function getFormEdit($iId, $aParams = array(), $aBrowseParams = array())

+ 23 - 4
modules/boonex/timeline/classes/BxTimelineTemplate.php

@@ -132,8 +132,16 @@ class BxTimelineTemplate extends BxBaseModNotificationsTemplate
 
     public function getJsCodePost($iOwnerId, $aParams = array(), $bWrap = true, $bDynamic = false)
     {
-        return $this->getJsCode('post', array(
+        $aGeneralParams = [];
+        $aRequestParams = $aParams;
+        if(isset($aParams['gparams'], $aParams['rparams'])) {
+            $aGeneralParams = $aParams['gparams'];
+            $aRequestParams = $aParams['rparams'];
+        }
+
+        return $this->getJsCode('post', array_merge(array(
             'bEmoji' => $this->_oConfig->isEmoji(),
+            'bAutoAttach' => $this->_oConfig->isEditorAutoAttach(),
             'iLimitAttachLinks' => $this->_oConfig->getLimitAttachLinks(),
             'sLimitAttachLinksErr' => bx_js_string(_t('_bx_timeline_txt_err_attach_links')),
             'oAttachedLinks' => $this->_oDb->getLinksBy(array(
@@ -143,16 +151,27 @@ class BxTimelineTemplate extends BxBaseModNotificationsTemplate
             )),
             'sVideosAutoplay' => $this->_oConfig->getVideosAutoplay(),
             'oRequestParams' => array_merge(array(
-                'type' => isset($aParams['type']) ? $aParams['type'] : BX_TIMELINE_TYPE_DEFAULT, 
+                'type' => isset($aRequestParams['type']) ? $aRequestParams['type'] : BX_TIMELINE_TYPE_DEFAULT, 
                 'owner_id' => $iOwnerId
-            ), $aParams)
-        ), $bWrap, $bDynamic);
+            ), $aRequestParams)
+        ), $aGeneralParams), $bWrap, $bDynamic);
     }
 
     public function getPostBlock($iOwnerId, $aParams = array())
     {
+        $CNF = &$this->_oConfig->CNF;
+
         $aForm = $this->getModule()->getFormPost($aParams);
 
+        if($this->_oConfig->isEditorAutoattach() && !empty($aForm['form_object'])) {
+            $aUploadersInfo = $aForm['form_object']->getUploadersInfo($CNF['FIELD_PHOTO']);
+            if(!empty($aUploadersInfo) && is_array($aUploadersInfo))
+                $aParams = [
+                    'gparams' => ['sAutoUploader' => $aUploadersInfo['name'], 'sAutoUploaderId' => $aUploadersInfo['id']],
+                    'rparams' => $aParams
+                ];
+        }
+
         return $this->parseHtmlByName('block_post.html', array (
             'style_prefix' => $this->_oConfig->getPrefix('style'),
             'js_object' => $this->_oConfig->getJsObject('post'),

+ 2 - 0
modules/boonex/timeline/install/langs/en.xml

@@ -50,6 +50,7 @@
     <string name="_bx_timeline_option_cache_item_engine"><![CDATA[Item cache engine (other than File option may require custom server setup)]]></string>
     <string name="_bx_timeline_option_cache_item_lifetime"><![CDATA[Item cache lifetime]]></string>
     <string name="_bx_timeline_option_enable_editor_toolbar"><![CDATA[Enable post form editor toolbar]]></string>
+    <string name="_bx_timeline_option_editor_auto_attach_insertion"><![CDATA[Treat images inserted in the editor as attachments]]></string>
     <string name="_bx_timeline_option_limit_attach_links"><![CDATA[Limit number of attached links (0 - no limit)]]></string>
 
     <string name="_bx_timeline_form_post"><![CDATA[Post]]></string>
@@ -322,6 +323,7 @@
     <string name="_bx_timeline_txt_msg_performed_action"><![CDATA[The action was successfully performed.]]></string>
     <string name="_bx_timeline_txt_msg_posted"><![CDATA[Posted successfully.]]></string>
     <string name="_bx_timeline_grid_action_err_delete"><![CDATA[Cannot delete the selected timeline events(s).]]></string>
+    <string name="_bx_timeline_txt_err_cannot_perform_insertion"><![CDATA[Cannot perform insertion.]]></string>
     <string name="_bx_timeline_txt_err_cannot_perform_action"><![CDATA[Cannot perform action. Please report.]]></string>
     <string name="_bx_timeline_txt_err_empty_post"><![CDATA[The post is empty.]]></string>
     <string name="_bx_timeline_txt_err_attach_links"><![CDATA[The maximum allowed number of attached links has been reached.]]></string>

+ 2 - 1
modules/boonex/timeline/install/sql/enable.sql

@@ -333,7 +333,8 @@ SET @iCategId = LAST_INSERT_ID();
 
 INSERT INTO `sys_options` (`name`, `value`, `category_id`, `caption`, `type`, `check`, `check_params`, `check_error`, `extra`, `order`) VALUES
 ('bx_timeline_enable_editor_toolbar', '', @iCategId, '_bx_timeline_option_enable_editor_toolbar', 'checkbox', '', '', '', '', 1),
-('bx_timeline_limit_attach_links', '0', @iCategId, '_bx_timeline_option_limit_attach_links', 'digit', '', '', '', '', 2);
+('bx_timeline_editor_auto_attach_insertion', '', @iCategId, '_bx_timeline_option_editor_auto_attach_insertion', 'checkbox', '', '', '', '', 2),
+('bx_timeline_limit_attach_links', '0', @iCategId, '_bx_timeline_option_limit_attach_links', 'digit', '', '', '', '', 10);
 
 
 -- PRIVACY 

+ 23 - 23
modules/boonex/timeline/js/post.js

@@ -16,6 +16,9 @@ function BxTimelinePost(oOptions) {
     this._sAnimationEffect = oOptions.sAnimationEffect == undefined ? 'slide' : oOptions.sAnimationEffect;
     this._iAnimationSpeed = oOptions.iAnimationSpeed == undefined ? 'slow' : oOptions.iAnimationSpeed;
     this._bEmoji = oOptions.bEmoji == undefined ? false : oOptions.bEmoji;
+    this._bAutoAttach = oOptions.bAutoAttach == undefined ? false : oOptions.bAutoAttach;
+    this._sAutoUploader = oOptions.sAutoUploader == undefined ? '' : oOptions.sAutoUploader;
+    this._sAutoUploaderId = oOptions.sAutoUploaderId == undefined ? '' : oOptions.sAutoUploaderId;
     this._iLimitAttachLinks = oOptions.iLimitAttachLinks == undefined ? 0 : oOptions.iLimitAttachLinks;
     this._sLimitAttachLinksErr = oOptions.sLimitAttachLinksErr == undefined ? '' : oOptions.sLimitAttachLinksErr;
     this._oAttachedLinks = oOptions.oAttachedLinks == undefined ? {} : oOptions.oAttachedLinks;
@@ -94,29 +97,8 @@ BxTimelinePost.prototype.initFormPost = function(sFormId)
         }
     });
 
-    if (typeof window.glOnSpaceEnterInEditor === 'undefined') {
-        window.glOnSpaceEnterInEditor = [];
-        window.glOnInsertImageInEditor = [];
-    }
-
-    window.glOnInsertImageInEditor.push(function (oFile) {
-        console.log(oFile);
-        const formData = new FormData();
-        formData.append("file", oFile);
-        fetch("/storage.php?o=sys_images_editor&t=sys_images_editor&a=upload", {
-                method: "POST",
-                body: formData
-            }
-        )
-        .then(response => response.json())
-        .then(result => {
-            console.log(result);
-            //process success url in result.link
-        })
-        .catch(error => {
-            //process error
-        });
-    });
+    if (typeof window.glOnSpaceEnterInEditor === 'undefined')
+        window.glOnSpaceEnterInEditor = [];    
 
     window.glOnSpaceEnterInEditor.push(function (sData, sSelector) {
         if(!oTextarea.is(sSelector))
@@ -142,6 +124,24 @@ BxTimelinePost.prototype.initFormPost = function(sFormId)
             $this.addAttachLink(oForm, sUrl);
         }
     });
+
+    if(this._bAutoAttach) {
+        if (typeof window.glOnInsertImageInEditor === 'undefined')
+            window.glOnInsertImageInEditor = [];
+
+        window.glOnInsertImageInEditor.push(function (oFile) {
+            const oFormData = new FormData();
+            oFormData.append('file', oFile);
+            oFormData.append('u', $this._sAutoUploader);
+            oFormData.append('uid', $this._sAutoUploaderId);
+
+            fetch($this._sActionsUrl + 'auto_attach_insertion/', {method: "POST", body: oFormData})
+            .then(response => response.json())
+            .then(result => {
+                processJsonData(result)
+            });
+        });
+   }
 };
 
 BxTimelinePost.prototype.beforeFormPostSubmit = function(oForm)