Merge to DOCx or ODT template
authordeb.monish <monish.deb@webaccessglobal.com>
Tue, 31 May 2016 07:19:34 +0000 (12:49 +0530)
committerdeb.monish <monish.deb@webaccessglobal.com>
Thu, 14 Jul 2016 18:05:43 +0000 (23:35 +0530)
CRM/Admin/Form/MessageTemplates.php
CRM/Core/BAO/File.php
CRM/Core/BAO/MessageTemplate.php
CRM/Core/SelectValues.php
CRM/Mailing/Page/AJAX.php
CRM/Utils/File.php
CRM/Utils/PDF/Document.php
templates/CRM/Admin/Form/MessageTemplates.tpl
templates/CRM/Form/attachmentjs.tpl
templates/CRM/Mailing/Form/InsertTokens.tpl

index 4ee63fc44470e44c733269c69cd95b45b997b197..f4d995eb32f0baa66d4c6cc28192d5772d178de5 100644 (file)
@@ -38,6 +38,7 @@
 class CRM_Admin_Form_MessageTemplates extends CRM_Admin_Form {
   // which (and whether) mailing workflow this template belongs to
   protected $_workflow_id = NULL;
+  protected $_documentID = NULL;
 
   public function preProcess() {
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
@@ -82,12 +83,23 @@ class CRM_Admin_Form_MessageTemplates extends CRM_Admin_Form {
       else {
         $selectedChild = 'user';
       }
+
+      $documentInfo = CRM_Core_BAO_File::getEntityFile('civicrm_msg_template', $this->_id, TRUE);
+      if (!empty($documentInfo)) {
+        foreach ($documentInfo as &$info) {
+          $defaults['file_type'] = array_search($info['mime_type'], CRM_Core_SelectValues::documentApplicationType());
+          $info['mime_type'] = $defaults['file_type'];
+          $this->_documentID = $info['fileID'];
+        }
+        $this->assign('attachment', $documentInfo);
+      }
+
       $cancelURL = CRM_Utils_System::url('civicrm/admin/messageTemplates', "selectedChild={$selectedChild}&reset=1");
       $cancelURL = str_replace('&amp;', '&', $cancelURL);
       $this->addButtons(
         array(
           array(
-            'type' => 'next',
+            'type' => 'upload',
             'name' => ts('Save'),
             'isDefault' => TRUE,
           ),
@@ -124,7 +136,18 @@ class CRM_Admin_Form_MessageTemplates extends CRM_Admin_Form {
       );
     }
     else {
-      parent::buildQuickForm();
+      $this->addButtons(array(
+          array(
+            'type' => 'upload',
+            'name' => $this->_action & CRM_Core_Action::DELETE ? ts('Delete') : ts('Save'),
+            'isDefault' => TRUE,
+          ),
+          array(
+            'type' => 'cancel',
+            'name' => ts('Cancel'),
+          ),
+        )
+      );
     }
 
     if ($this->_action & CRM_Core_Action::DELETE) {
@@ -144,6 +167,11 @@ class CRM_Admin_Form_MessageTemplates extends CRM_Admin_Form {
     $this->applyFilter('__ALL__', 'trim');
     $this->add('text', 'msg_title', ts('Message Title'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_MessageTemplate', 'msg_title'), TRUE);
 
+    $this->add('select', 'file_type', ts('File Type'), CRM_Core_SelectValues::documentFormat());
+
+    $this->addElement('file', "file_id", ts('Upload Document'), 'size=30 maxlength=60');
+    $this->addUploadElement("file_id");
+
     $this->add('text', 'msg_subject',
       ts('Message Subject'),
       CRM_Core_DAO::getAttribute('CRM_Core_DAO_MessageTemplate', 'msg_subject')
@@ -188,12 +216,49 @@ class CRM_Admin_Form_MessageTemplates extends CRM_Admin_Form {
 
     $this->add('checkbox', 'is_active', ts('Enabled?'));
 
+    $this->addFormRule(array(__CLASS__, 'formRule'), $this);
+
     if ($this->_action & CRM_Core_Action::VIEW) {
       $this->freeze();
       CRM_Utils_System::setTitle(ts('View System Default Message Template'));
     }
   }
 
+  /**
+   * Global form rule.
+   *
+   * @param array $fields
+   *   The input form values.
+   * @param array $files
+   *   The uploaded files if any.
+   *
+   * @return array
+   *   array of errors
+   */
+  public static function formRule($params, $files, $self) {
+    $errors = array();
+
+    //empty file upload validation for odt/docx template
+    if (empty($files['file_id']['tmp_name']) && in_array($params['file_type'], array('odt', 'docx'))) {
+      //On edit page of docx/odt message template if user changes file type but forgot to upload document
+      if (!empty($self->_documentID)) {
+        $fileDAO = new CRM_Core_DAO_File();
+        $fileDAO->id = $self->_documentID;
+        if ($fileDAO->find(TRUE) &&
+          $fileDAO->mime_type != CRM_Utils_Array::value($params['file_type'], CRM_Core_SelectValues::documentApplicationType())
+        ) {
+          $errors['file_id'] = ts('Please upload document');
+        }
+      }
+      else {
+        $errors['file_id'] = ts('Please upload document');
+      }
+
+    }
+
+    return $errors;
+  }
+
   /**
    * Process the form submission.
    */
@@ -209,12 +274,31 @@ class CRM_Admin_Form_MessageTemplates extends CRM_Admin_Form {
       $params = array();
 
       // store the submitted values in an array
-      $params = $this->exportValues();
+      $params = $this->controller->exportValues($this->_name);
 
       if ($this->_action & CRM_Core_Action::UPDATE) {
         $params['id'] = $this->_id;
       }
 
+      if (in_array($params['file_type'], array('odt', 'docx'))) {
+        unset($params['msg_html']);
+        unset($params['msg_text']);
+        CRM_Utils_File::formatFile($params, 'file_id');
+      }
+      // delete related file refernces if html/text/pdf template are chosen over document
+      elseif (!empty($this->_id)) {
+        $entityFileDAO = new CRM_Core_DAO_EntityFile();
+        $entityFileDAO->entity_id = $this->_id;
+        $entityFileDAO->entity_table = 'civicrm_msg_template';
+        if ($entityFileDAO->find(TRUE)) {
+          $fileDAO = new CRM_Core_DAO_File();
+          $fileDAO->id = $entityFileDAO->file_id;
+          $fileDAO->find(TRUE);
+          $entityFileDAO->delete();
+          $fileDAO->delete();
+        }
+      }
+
       if ($this->_workflow_id) {
         $params['workflow_id'] = $this->_workflow_id;
         $params['is_active'] = TRUE;
index 9514b2044bb82dd9438058ac010777be5dbeb01c..8f1fcf6bdb257a27c43b9637cf3c04cb5aebbd0d 100644 (file)
@@ -170,6 +170,8 @@ class CRM_Core_BAO_File extends CRM_Core_DAO_File {
 
     // lets call the post hook here so attachments code can do the right stuff
     CRM_Utils_Hook::post($op, 'File', $fileDAO->id, $fileDAO);
+
+    return $fileDAO;
   }
 
   /**
@@ -532,8 +534,6 @@ AND       CEF.entity_id    = %2";
 
     $numAttachments = Civi::settings()->get('max_attachments');
 
-    $now = date('YmdHis');
-
     // setup all attachments
     for ($i = 1; $i <= $numAttachments; $i++) {
       $attachName = "attachFile_$i";
@@ -551,17 +551,13 @@ AND       CEF.entity_id    = %2";
 
         // we dont care if the file is empty or not
         // CRM-7448
-        $fileParams = array(
-          'uri' => $formValues[$attachName]['name'],
-          'type' => $formValues[$attachName]['type'],
-          'location' => $formValues[$attachName]['name'],
+        $extraParams = array(
           'description' => $formValues[$attachDesc],
-          'upload_date' => $now,
           'tag' => $tagParams,
           'attachment_taglist' => CRM_Utils_Array::value($attachFreeTags, $formValues, array()),
         );
 
-        $params[$attachName] = $fileParams;
+        CRM_Utils_File::formatFile($formValues, $attachName, $extraParams);
       }
     }
   }
index b2ee6bded49f446a405582d26b6843998b24f024..4df5bed66640d31867bfa9831feadcba9bf18946 100644 (file)
@@ -86,10 +86,32 @@ class CRM_Core_BAO_MessageTemplate extends CRM_Core_DAO_MessageTemplate {
     $hook = empty($params['id']) ? 'create' : 'edit';
     CRM_Utils_Hook::pre($hook, 'MessageTemplate', CRM_Utils_Array::value('id', $params), $params);
 
+    if (!empty($params['file_id']) && is_array($params['file_id']) && count($params['file_id'])) {
+      $fileParams = $params['file_id'];
+      unset($params['file_id']);
+    }
+
     $messageTemplates = new CRM_Core_DAO_MessageTemplate();
     $messageTemplates->copyValues($params);
     $messageTemplates->save();
 
+    if (!empty($fileParams)) {
+      $params['file_id'] = $fileParams;
+      $fileDao = CRM_Core_BAO_File::filePostProcess(
+        $params['file_id']['location'],
+        NULL,
+        'civicrm_msg_template',
+        $messageTemplates->id,
+        NULL,
+        TRUE,
+        $params['file_id'],
+        'file_id',
+        $params['file_id']['type']
+      );
+
+      $messageTemplates->save();
+    }
+
     CRM_Utils_Hook::post($hook, 'MessageTemplate', $messageTemplates->id, $messageTemplates);
     return $messageTemplates;
   }
index ed65f23c96a0b6fc6d576f2ae9092a4f0074749f..005b13086a16307914f18c3db3455aac6b75e51a 100644 (file)
@@ -1087,4 +1087,17 @@ class CRM_Core_SelectValues {
     );
   }
 
+  /**
+   * Application type of document.
+   *
+   * @return array
+   */
+  public static function documentApplicationType() {
+    return array(
+      'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+      'odt' => 'application/vnd.oasis.opendocument.text',
+    );
+  }
+
+
 }
index 855967c01cabb4c5db0755501ae9f40e4c66fd3a..799c71953b0c61559274b0df0c1f8a8c99ac2a5e 100644 (file)
@@ -54,6 +54,13 @@ class CRM_Mailing_Page_AJAX {
       'pdf_format_id' => $messageTemplate->pdf_format_id,
     );
 
+    $documentInfo = CRM_Core_BAO_File::getEntityFile('civicrm_msg_template', $templateId);
+    foreach ((array) $documentInfo as $info) {
+      $messages['file_type'] = array_search($info['mime_type'], CRM_Core_SelectValues::documentApplicationType());
+      $messages['document_path'] = $info['fullPath'];
+      $messages['mime_type'] = $info['mime_type'];
+    }
+
     CRM_Utils_JSON::output($messages);
   }
 
index 16996e8f2462d066e762a0b5b8df89c5fabaff36..087a484746cefe75a1566bfba7f159c524110710 100644 (file)
@@ -766,4 +766,19 @@ HTACCESS;
     return TRUE;
   }
 
+  public static function formatFile(&$param, $fileName, $extraParams = array()) {
+    if (empty($param[$fileName])) {
+      return;
+    }
+
+    $fileParams = array(
+      'uri' => $param[$fileName]['name'],
+      'type' => $param[$fileName]['type'],
+      'location' => $param[$fileName]['name'],
+      'upload_date' => date('YmdHis'),
+    ) + $extraParams;
+
+    $param[$fileName] = $fileParams;
+  }
+
 }
index 4b990cf74a62981fd0affdb8d2a58a4b99bc46e8..4dba35403f7882db2adb08c8915e6e48b6e230e9 100644 (file)
@@ -95,4 +95,8 @@ class CRM_Utils_PDF_Document {
     return \PhpOffice\PhpWord\Shared\Converter::pointToTwip($point);
   }
 
+  public static function docReader($path) {
+    return \PhpOffice\PhpWord\IOFactory::load($path);
+
+  }
 }
index 1b33dc60fe7e7bda7b200dfe3d143110e50c5478..dd440e15eb2f2bb5a5ca0e7ff194af97bd03d4d7 100644 (file)
                 <br /><span class="description html-adjust">{ts}Descriptive title of message - used for template selection.{/ts}</span>
             </td>
         </tr>
+        <tr>
+           <td class="label-left">{$form.file_type.label}</td>
+            <td>{$form.file_type.html}
+                <br /><span class="description html-adjust">{ts}Choose the file type{/ts}</span>
+            </td>
+        </tr>
         <tr>
             <td class="label-left">{$form.msg_subject.label}</td>
             <td>
             </td>
         </tr>
         <tr>
+            <td class="label-left">{$form.file_id.label}</td>
+            <td>{$form.file_id.html}
+              {if $attachment}
+                 {foreach from=$attachment key=attKey item=attVal}
+                 <div class="crm-attachment-wrapper crm-entity" id="file_{$attVal.fileID}">
+                   <strong><a class="crm-attachment" href="{$attVal.url}">{$attVal.cleanName}</a></strong>
+                   {if $attVal.description}&nbsp;-&nbsp;{$attVal.description}{/if}
+                   {if $attVal.deleteURLArgs}
+                    <a href="#" class="crm-hover-button delete-attachment" data-mimetype="{$attVal.mime_type}" data-filename="{$attVal.cleanName}" data-args="{$attVal.deleteURLArgs}" title="{ts}Delete File{/ts}"><span class="icon delete-icon"></span></a>
+                   {/if}
+                   {include file="CRM/Form/attachmentjs.tpl" context='MessageTemplate'}
+                 {/foreach}
+              {/if}
+                <br /><span class="description html-adjust">{ts}Upload the document file{/ts}</span>
+            </td>
+        </tr>
+        <tr>
   </table>
 
-      <div class="crm-accordion-wrapper crm-html_email-accordion ">
+      <div id="msg_html" class="crm-accordion-wrapper crm-html_email-accordion ">
         <div class="crm-accordion-header">
             {ts}HTML Format{/ts}
             {help id="id-message-text" file="CRM/Contact/Form/Task/Email.hlp"}
         </div><!-- /.crm-accordion-body -->
       </div><!-- /.crm-accordion-wrapper -->
 
-      <div class="crm-accordion-wrapper crm-plaint_text_email-accordion ">
+      <div id="msg_text" class="crm-accordion-wrapper crm-plaint_text_email-accordion ">
         <div class="crm-accordion-header">
                 {ts}Plain-Text Format{/ts}
         </div><!-- /.crm-accordion-header -->
 </div>
 </div> <!-- end of crm-form-block -->
 {include file="CRM/Mailing/Form/InsertTokens.tpl"}
+
+{literal}
+  <script type='text/javascript'>
+    CRM.$(function($) {
+      var mimeType = null;
+      // if default file is selected then hide the file upload field
+      if ($('a.delete-attachment').length) {
+        $('#file_id').hide();
+        mimeType = $('a.delete-attachment').data('mimetype');
+      }
+
+      $('#file_type').on('change', function(){
+        toggleByFileType(this.value);
+      });
+      toggleByFileType($('#file_type').val());
+
+      function toggleByFileType(type) {
+        var show = (type == 'odt' || type == 'docx') ? false : true;
+        $("#msg_html").toggle(show);
+        $("#msg_text").toggle(show);
+        $("#file_id").parent().parent().toggle(!show);
+
+        // auto file type validation
+        if (!show) {
+          var validType = (type == 'odt') ? 'application/vnd.oasis.opendocument.text' : 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
+          $("#file_id").attr('accept', validType);
+        }
+
+        // when you change file type other than the type of default uploaded document
+        if (mimeType) {
+          var hide = (mimeType != type) ? true : false;
+          $("#file_id").toggle(hide);
+          $('.crm-attachment-wrapper').toggle(!hide);
+        }
+      }
+    });
+  </script>
+{/literal}
index 19823c2637440e1ad3758948caf607e432344293..378aaf1919f49f8a04e65125176bedbc89d2bea4 100644 (file)
@@ -15,6 +15,9 @@
         request.done(function() {
           $el.trigger('crmPopupFormSuccess');
           $row.remove();
+          {/literal}{if $context EQ 'MessageTemplate'}{literal}
+            $('#file_id').show();
+          {/literal}{/if}{literal}
         });
       });
       e.preventDefault();
index 64b5000b886c6e56b410660591bca3f783c9aeda..75a18fc4192a63d92322d51b528ffc1d75f9d6e2 100644 (file)
@@ -131,10 +131,19 @@ function selectValue( val, prefix) {
   var dataUrl = {/literal}"{crmURL p='civicrm/ajax/template' h=0 }"{literal};
 
   cj.post( dataUrl, {tid: val}, function( data ) {
+    if (data.document_path) {
+      cj("#document").attr('data', data.document_path);
+      cj("#document").attr('type', data.mime_type);
+      cj("#document embed").attr('type', data.mime_type);
+      cj('#document embed').attr('src', data.document_path);
+      console.log(data.document_path);
+    }
+
     if ( !isPDF ) {
       if (prefix == "SMS") {
           text_message = "sms_text_message";
       }
+
       if ( data.msg_text ) {
         cj("#"+text_message).val( data.msg_text );
         cj("div.text").show();