function wordmailmerge_civicrm_buildForm($formName, &$form)
{
    require_once 'CRM/Core/DAO/MessageTemplate.php';
    require_once 'CRM/Core/BAO/File.php';
    require_once 'CRM/Core/DAO.php';
    if ($formName == 'CRM_Admin_Form_MessageTemplates') {
        $action = $form->getVar('_action');
        $template = CRM_Core_Smarty::singleton();
        $form->assign('action', $action);
        $templatePath = realpath(dirname(__FILE__) . "/templates");
        $config = CRM_Core_Config::singleton();
        if ($action == CRM_Core_Action::UPDATE) {
            $msgTemplateId = $form->getVar('_defaultValues')['id'];
            $sql = "SELECT * FROM veda_civicrm_wordmailmerge WHERE msg_template_id = %1";
            $params = array(1 => array($msgTemplateId, 'Integer'));
            $dao = CRM_Core_DAO::executeQuery($sql, $params);
            while ($dao->fetch()) {
                $fileId = $dao->file_id;
            }
            if (!empty($fileId)) {
                $mysql = "SELECT * FROM civicrm_file WHERE id = %1";
                $params = array(1 => array($fileId, 'Integer'));
                $dao = CRM_Core_DAO::executeQuery($mysql, $params);
                while ($dao->fetch()) {
                    $default['fileID'] = $dao->id;
                    $default['mime_type'] = $dao->mime_type;
                    $default['fileName'] = $dao->uri;
                    $default['cleanName'] = CRM_Utils_File::cleanFileName($dao->uri);
                    $default['fullPath'] = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $dao->uri;
                    $default['url'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$dao->id}&eid={$msgTemplateId}");
                    $default['href'] = "<a href=\"{$default['url']}\">{$default['cleanName']}</a>";
                    $default['tag'] = CRM_Core_BAO_EntityTag::getTag($dao->id, 'civicrm_file');
                    $default['deleteURLArgs'] = CRM_Core_BAO_File::deleteURLArgs('civicrm_msg_template', $msgTemplateId, $dao->id);
                }
                $defaults[$dao->id] = $default;
                $form->assign('defaults', $defaults);
            }
        }
        CRM_Core_BAO_File::buildAttachment($form, 'civicrm_msg_template', '', 1);
        $session = CRM_Core_Session::singleton();
        $session->pushUserContext(CRM_Utils_System::url('civicrm/admin/messageTemplates', 'reset=1'));
        CRM_Core_Region::instance('page-body')->add(array('template' => "{$templatePath}/CRM/Wordmailmerge/testfield.tpl"));
    }
}
 /**
  * Build the entity-specific custom data into the group tree on a per-field basis
  *
  * @param object $dao
  *   Object representing the custom field to be populated into the groupTree.
  * @param array $groupTree
  *   (reference) the group tree being build.
  * @param string $table
  *   Table name.
  * @param int $groupID
  *   Custom group ID.
  * @param int $fieldID
  *   Custom field ID.
  */
 public static function buildCustomFieldData($dao, &$groupTree, $table, $groupID, $fieldID)
 {
     $column = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
     $idName = "{$table}_id";
     $fieldName = "{$table}_{$column}";
     $dataType = $groupTree[$groupID]['fields'][$fieldID]['data_type'];
     if ($dataType == 'File') {
         if (isset($dao->{$fieldName})) {
             $config = CRM_Core_Config::singleton();
             $fileDAO = new CRM_Core_DAO_File();
             $fileDAO->id = $dao->{$fieldName};
             if ($fileDAO->find(TRUE)) {
                 $entityIDName = "{$table}_entity_id";
                 $customValue['id'] = $dao->{$idName};
                 $customValue['data'] = $fileDAO->uri;
                 $customValue['fid'] = $fileDAO->id;
                 $customValue['fileURL'] = CRM_Utils_System::url('civicrm/file', "reset=1&id={$fileDAO->id}&eid={$dao->{$entityIDName}}");
                 $customValue['displayURL'] = NULL;
                 $deleteExtra = ts('Are you sure you want to delete attached file.');
                 $deleteURL = array(CRM_Core_Action::DELETE => array('name' => ts('Delete Attached File'), 'url' => 'civicrm/file', 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&fid=%%fid%%&action=delete', 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&amp;confirmed=1\'; else return false;"'));
                 $customValue['deleteURL'] = CRM_Core_Action::formLink($deleteURL, CRM_Core_Action::DELETE, array('id' => $fileDAO->id, 'eid' => $dao->{$entityIDName}, 'fid' => $fieldID), ts('more'), FALSE, 'file.manage.delete', 'File', $fileDAO->id);
                 $customValue['deleteURLArgs'] = CRM_Core_BAO_File::deleteURLArgs($table, $dao->{$entityIDName}, $fileDAO->id);
                 $customValue['fileName'] = CRM_Utils_File::cleanFileName(basename($fileDAO->uri));
                 if ($fileDAO->mime_type == "image/jpeg" || $fileDAO->mime_type == "image/pjpeg" || $fileDAO->mime_type == "image/gif" || $fileDAO->mime_type == "image/x-png" || $fileDAO->mime_type == "image/png") {
                     $customValue['displayURL'] = $customValue['fileURL'];
                     $entityId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile', $fileDAO->id, 'entity_id', 'file_id');
                     $customValue['imageURL'] = str_replace('persist/contribute', 'custom', $config->imageUploadURL) . $fileDAO->uri;
                     list($path) = CRM_Core_BAO_File::path($fileDAO->id, $entityId, NULL, NULL);
                     if ($path && file_exists($path)) {
                         list($imageWidth, $imageHeight) = getimagesize($path);
                         list($imageThumbWidth, $imageThumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($imageWidth, $imageHeight);
                         $customValue['imageThumbWidth'] = $imageThumbWidth;
                         $customValue['imageThumbHeight'] = $imageThumbHeight;
                     }
                 }
             }
         } else {
             $customValue = array('id' => $dao->{$idName}, 'data' => '');
         }
     } else {
         $customValue = array('id' => $dao->{$idName}, 'data' => $dao->{$fieldName});
     }
     if (!array_key_exists('customValue', $groupTree[$groupID]['fields'][$fieldID])) {
         $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array();
     }
     if (empty($groupTree[$groupID]['fields'][$fieldID]['customValue'])) {
         $groupTree[$groupID]['fields'][$fieldID]['customValue'] = array(1 => $customValue);
     } else {
         $groupTree[$groupID]['fields'][$fieldID]['customValue'][] = $customValue;
     }
 }
 function postProcess()
 {
     $values = $this->_contactIds;
     $config = CRM_Core_Config::singleton();
     $msg_id = $this->_submitValues['message_template'];
     if (!empty($msg_id)) {
         $mysql = " SELECT * FROM veda_civicrm_wordmailmerge WHERE msg_template_id = %1";
         $params = array(1 => array($msg_id, 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($mysql, $params);
         //$dao = CRM_Core_DAO::executeQuery($mysql);
         while ($dao->fetch()) {
             $fileId = $dao->file_id;
         }
         $sql = "SELECT * FROM civicrm_file WHERE id = %1";
         $params = array(1 => array($fileId, 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($sql, $params);
         //$dao = CRM_Core_DAO::executeQuery($sql);
         while ($dao->fetch()) {
             $default['fileID'] = $dao->id;
             $default['mime_type'] = $dao->mime_type;
             $default['fileName'] = $dao->uri;
             $default['cleanName'] = CRM_Utils_File::cleanFileName($dao->uri);
             $default['fullPath'] = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $dao->uri;
             $default['deleteURLArgs'] = CRM_Core_BAO_File::deleteURLArgs('civicrm_file', $msg_id, $dao->id);
         }
         $defaults[$dao->id] = $default;
         $this->assign('defaults', $defaults);
         $noofContact = count($this->_contactIds);
         require_once $config->extensionsDir . '/uk.co.vedaconsulting.module.wordmailmerge/tinybutstrong/tbs_class.php';
         require_once $config->extensionsDir . '/uk.co.vedaconsulting.module.wordmailmerge/tinybutstrong-opentbs/tbs_plugin_opentbs.php';
         $TBS = new clsTinyButStrong();
         // new instance of TBS
         $TBS->Plugin(TBS_INSTALL, OPENTBS_PLUGIN);
         // load the OpenTBS plugin
         $template = $default['fullPath'];
         // contactrows to check for duplicate address
         $contactrows = array();
         foreach ($values as $key => $value) {
             $SelectedcontactID = $values[$key];
             // get the details for all selected contacts
             list($contactDetails) = CRM_Utils_Token::getTokenDetails(array($SelectedcontactID), $this->_returnProperties, NULL, NULL, FALSE, $this->_allTokens);
             // populate contactrows array to check dupliacte address
             $contactrows[$SelectedcontactID] = $contactDetails[$SelectedcontactID];
         }
         // if merge_letter_for_same_address selected check for duplicate address
         if (isset($this->_submitValues['merge_letter_for_same_address']) && $this->_submitValues['merge_letter_for_same_address']) {
             CRM_Core_BAO_Address::mergeSameAddress($contactrows);
         }
         foreach ($values as $key => $value) {
             if ($key < $noofContact) {
                 $selectedCID = $values[$key];
                 $contactFormatted = array();
                 // if contact_id found in filtered contactrows array get contact details from contactrows
                 if (array_key_exists($selectedCID, $contactrows)) {
                     $contactFormatted[$selectedCID] = $contactrows[$selectedCID];
                     $membershipFormatted = array();
                     if ($this->_searchFrom == 'member' && isset($contactFormatted[$selectedCID]['membership_id'])) {
                         $membershipFormatted = CRM_Utils_Token::getMembershipTokenDetails($contactFormatted[$selectedCID]['membership_id']);
                     }
                     foreach ($this->_tokenMerge as $atKey => $atValue) {
                         // Replace hook tokens
                         $explodedTokenName = explode('.', $atValue['token_name']);
                         // this is fixed by assigning 'address_block' token into 'contact' token array // gopi@vedaconsulting.co.uk
                         //need to do proper fix seems token named as contact.address_block
                         // $atValue['token_name'] = ($atValue['token_name'] == 'address_block') ? 'contact.'.$atValue['token_name'] : $atValue['token_name'];
                         if (array_key_exists($atValue['token_name'], $contactFormatted[$selectedCID])) {
                             if (!empty($explodedTokenName[1]) && $explodedTokenName[0] != 'contact') {
                                 $vars[$key][$explodedTokenName[0]][$explodedTokenName[1]] = $contactFormatted[$selectedCID][$atValue['token_name']];
                             } else {
                                 $vars[$key][$atValue['token_name']] = $contactFormatted[$selectedCID][$atValue['token_name']];
                             }
                         } else {
                             if ($explodedTokenName[0] == 'membership') {
                                 $explodedTokenName[1] = $explodedTokenName[1] == 'membership_id' ? 'id' : $explodedTokenName[1];
                                 $vars[$key][$explodedTokenName[0]][$explodedTokenName[1]] = CRM_Utils_Token::getMembershipTokenReplacement($explodedTokenName[1], $membershipFormatted[$contactFormatted[$selectedCID]['membership_id']]);
                             } else {
                                 $vars[$key][$atValue['token_name']] = CRM_Utils_Token::getContactTokenReplacement($atValue['token_name'], $contactFormatted[$selectedCID], FALSE, FALSE);
                             }
                         }
                         //need to do proper fix, token_name.date seems not returning null value if not found
                         if ($explodedTokenName[0] == 'token_name' && !is_array($vars[$key]['token_name'])) {
                             $vars[$key][$atValue['token_name']] = '';
                         }
                     }
                     //to skip error, if by chance using membership token in 'find contact' search
                     if ($this->_searchFrom != 'member') {
                         foreach (CRM_Core_SelectValues::membershipTokens() as $token => $label) {
                             $token = str_replace(array('{', '}'), "", $token);
                             $tokenNames = explode('.', $token);
                             $vars[$key]['membership'][$tokenNames[1]] = $label;
                         }
                     }
                     foreach ($vars[$key] as $varKey => $varValue) {
                         $explodeValues = explode('.', $varKey);
                         if (isset($explodeValues[1]) && !empty($explodeValues[1])) {
                             $vars[$key][$explodeValues[0]][$explodeValues[1]] = $vars[$key][$varKey];
                             unset($vars[$key][$varKey]);
                         }
                     }
                     // blank lines removed while creating the address_block - gopi@vedaconsulting.co.uk
                     /*if (!empty($vars[$key]['contact']['address_block'])) {
                         $vars[$key]['contact']['address_block'] = str_replace('<br />', "", $vars[$key]['contact']['address_block']);
                       }*/
                     $TBS->LoadTemplate($template, OPENTBS_ALREADY_UTF8);
                     $TBS->MergeBlock(self::TOKEN_VAR_NAME, $vars);
                 }
             }
         }
         $output_file_name = 'CiviCRMWordExport.docx';
         $TBS->Show(OPENTBS_DOWNLOAD, $output_file_name);
         CRM_Utils_System::civiExit();
     }
     parent::postProcess();
 }