PageRenderTime 50ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/sites/all/modules/contrib/civicrm/CRM/Core/Form/Task/PDFLetterCommon.php

https://gitlab.com/virtualrealms/d7civicrm
PHP | 339 lines | 227 code | 27 blank | 85 comment | 28 complexity | c6c853b298e2aeb4407e298361631aeb MD5 | raw file
  1. <?php
  2. /*
  3. +--------------------------------------------------------------------+
  4. | CiviCRM version 5 |
  5. +--------------------------------------------------------------------+
  6. | Copyright CiviCRM LLC (c) 2004-2019 |
  7. +--------------------------------------------------------------------+
  8. | This file is a part of CiviCRM. |
  9. | |
  10. | CiviCRM is free software; you can copy, modify, and distribute it |
  11. | under the terms of the GNU Affero General Public License |
  12. | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
  13. | |
  14. | CiviCRM is distributed in the hope that it will be useful, but |
  15. | WITHOUT ANY WARRANTY; without even the implied warranty of |
  16. | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
  17. | See the GNU Affero General Public License for more details. |
  18. | |
  19. | You should have received a copy of the GNU Affero General Public |
  20. | License and the CiviCRM Licensing Exception along |
  21. | with this program; if not, contact CiviCRM LLC |
  22. | at info[AT]civicrm[DOT]org. If you have questions about the |
  23. | GNU Affero General Public License or the licensing of CiviCRM, |
  24. | see the CiviCRM license FAQ at http://civicrm.org/licensing |
  25. +--------------------------------------------------------------------+
  26. */
  27. /**
  28. *
  29. * @package CRM
  30. * @copyright CiviCRM LLC (c) 2004-2019
  31. */
  32. /**
  33. * This is the base class for common PDF/Doc Merge functionality.
  34. * Most CRM_*_Form_Task_PDFLetterCommon classes extend the Contact version
  35. * but the assumptions there are not always appropriate for other classes
  36. * resulting in code duplication and unexpected dependencies.
  37. * The intention is that common functionality can be moved here and the other
  38. * classes cleaned up.
  39. * Keep old-style token handling out of this class.
  40. */
  41. class CRM_Core_Form_Task_PDFLetterCommon {
  42. /**
  43. * @var CRM_Core_Form $form
  44. */
  45. public static function preProcess(&$form) {
  46. CRM_Utils_System::setTitle('Print/Merge Document');
  47. }
  48. /**
  49. * Build the form object.
  50. *
  51. * @var CRM_Core_Form $form
  52. */
  53. public static function buildQuickForm(&$form) {
  54. // This form outputs a file so should never be submitted via ajax
  55. $form->preventAjaxSubmit();
  56. //Added for CRM-12682: Add activity subject and campaign fields
  57. CRM_Campaign_BAO_Campaign::addCampaign($form);
  58. $form->add(
  59. 'text',
  60. 'subject',
  61. ts('Activity Subject'),
  62. ['size' => 45, 'maxlength' => 255],
  63. FALSE
  64. );
  65. $form->add('static', 'pdf_format_header', NULL, ts('Page Format: %1', [1 => '<span class="pdf-format-header-label"></span>']));
  66. $form->addSelect('format_id', [
  67. 'label' => ts('Select Format'),
  68. 'placeholder' => ts('Default'),
  69. 'entity' => 'message_template',
  70. 'field' => 'pdf_format_id',
  71. 'option_url' => 'civicrm/admin/pdfFormats',
  72. ]);
  73. $form->add(
  74. 'select',
  75. 'paper_size',
  76. ts('Paper Size'),
  77. [0 => ts('- default -')] + CRM_Core_BAO_PaperSize::getList(TRUE),
  78. FALSE,
  79. ['onChange' => "selectPaper( this.value ); showUpdateFormatChkBox();"]
  80. );
  81. $form->add('static', 'paper_dimensions', NULL, ts('Width x Height'));
  82. $form->add(
  83. 'select',
  84. 'orientation',
  85. ts('Orientation'),
  86. CRM_Core_BAO_PdfFormat::getPageOrientations(),
  87. FALSE,
  88. ['onChange' => "updatePaperDimensions(); showUpdateFormatChkBox();"]
  89. );
  90. $form->add(
  91. 'select',
  92. 'metric',
  93. ts('Unit of Measure'),
  94. CRM_Core_BAO_PdfFormat::getUnits(),
  95. FALSE,
  96. ['onChange' => "selectMetric( this.value );"]
  97. );
  98. $form->add(
  99. 'text',
  100. 'margin_left',
  101. ts('Left Margin'),
  102. ['size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"],
  103. TRUE
  104. );
  105. $form->add(
  106. 'text',
  107. 'margin_right',
  108. ts('Right Margin'),
  109. ['size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"],
  110. TRUE
  111. );
  112. $form->add(
  113. 'text',
  114. 'margin_top',
  115. ts('Top Margin'),
  116. ['size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"],
  117. TRUE
  118. );
  119. $form->add(
  120. 'text',
  121. 'margin_bottom',
  122. ts('Bottom Margin'),
  123. ['size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"],
  124. TRUE
  125. );
  126. $config = CRM_Core_Config::singleton();
  127. /** CRM-15883 Suppressing Stationery path field until we switch from DOMPDF to a library that supports it.
  128. * if ($config->wkhtmltopdfPath == FALSE) {
  129. * $form->add(
  130. * 'text',
  131. * 'stationery',
  132. * ts('Stationery (relative path to PDF you wish to use as the background)'),
  133. * array('size' => 25, 'maxlength' => 900, 'onkeyup' => "showUpdateFormatChkBox();"),
  134. * FALSE
  135. * );
  136. * }
  137. */
  138. $form->add('checkbox', 'bind_format', ts('Always use this Page Format with the selected Template'));
  139. $form->add('checkbox', 'update_format', ts('Update Page Format (this will affect all templates that use this format)'));
  140. $form->assign('useThisPageFormat', ts('Always use this Page Format with the new template?'));
  141. $form->assign('useSelectedPageFormat', ts('Should the new template always use the selected Page Format?'));
  142. $form->assign('totalSelectedContacts', count($form->_contactIds));
  143. $form->add('select', 'document_type', ts('Document Type'), CRM_Core_SelectValues::documentFormat());
  144. $documentTypes = implode(',', CRM_Core_SelectValues::documentApplicationType());
  145. $form->addElement('file', "document_file", 'Upload Document', 'size=30 maxlength=255 accept="' . $documentTypes . '"');
  146. $form->addUploadElement("document_file");
  147. CRM_Mailing_BAO_Mailing::commonCompose($form);
  148. $buttons = [];
  149. if ($form->get('action') != CRM_Core_Action::VIEW) {
  150. $buttons[] = [
  151. 'type' => 'upload',
  152. 'name' => ts('Download Document'),
  153. 'isDefault' => TRUE,
  154. 'icon' => 'fa-download',
  155. ];
  156. $buttons[] = [
  157. 'type' => 'submit',
  158. 'name' => ts('Preview'),
  159. 'subName' => 'preview',
  160. 'icon' => 'fa-search',
  161. 'isDefault' => FALSE,
  162. ];
  163. }
  164. $buttons[] = [
  165. 'type' => 'cancel',
  166. 'name' => $form->get('action') == CRM_Core_Action::VIEW ? ts('Done') : ts('Cancel'),
  167. ];
  168. $form->addButtons($buttons);
  169. $form->addFormRule(['CRM_Core_Form_Task_PDFLetterCommon', 'formRule'], $form);
  170. }
  171. /**
  172. * Set default values.
  173. */
  174. public static function setDefaultValues() {
  175. $defaultFormat = CRM_Core_BAO_PdfFormat::getDefaultValues();
  176. $defaultFormat['format_id'] = $defaultFormat['id'];
  177. return $defaultFormat;
  178. }
  179. /**
  180. * Form rule.
  181. *
  182. * @param array $fields
  183. * The input form values.
  184. * @param array $files
  185. * @param array $self
  186. * Additional values form 'this'.
  187. *
  188. * @return bool
  189. * TRUE if no errors, else array of errors.
  190. */
  191. public static function formRule($fields, $files, $self) {
  192. $errors = [];
  193. $template = CRM_Core_Smarty::singleton();
  194. // If user uploads non-document file other than odt/docx
  195. if (empty($fields['template']) &&
  196. !empty($files['document_file']['tmp_name']) &&
  197. array_search($files['document_file']['type'], CRM_Core_SelectValues::documentApplicationType()) == NULL
  198. ) {
  199. $errors['document_file'] = ts('Invalid document file format');
  200. }
  201. //Added for CRM-1393
  202. if (!empty($fields['saveTemplate']) && empty($fields['saveTemplateName'])) {
  203. $errors['saveTemplateName'] = ts("Enter name to save message template");
  204. }
  205. if (!is_numeric($fields['margin_left'])) {
  206. $errors['margin_left'] = 'Margin must be numeric';
  207. }
  208. if (!is_numeric($fields['margin_right'])) {
  209. $errors['margin_right'] = 'Margin must be numeric';
  210. }
  211. if (!is_numeric($fields['margin_top'])) {
  212. $errors['margin_top'] = 'Margin must be numeric';
  213. }
  214. if (!is_numeric($fields['margin_bottom'])) {
  215. $errors['margin_bottom'] = 'Margin must be numeric';
  216. }
  217. return empty($errors) ? TRUE : $errors;
  218. }
  219. /**
  220. * Handle the template processing part of the form
  221. */
  222. public static function processTemplate(&$formValues) {
  223. $html_message = CRM_Utils_Array::value('html_message', $formValues);
  224. // process message template
  225. if (!empty($formValues['saveTemplate']) || !empty($formValues['updateTemplate'])) {
  226. $messageTemplate = [
  227. 'msg_text' => NULL,
  228. 'msg_html' => $formValues['html_message'],
  229. 'msg_subject' => NULL,
  230. 'is_active' => TRUE,
  231. ];
  232. $messageTemplate['pdf_format_id'] = 'null';
  233. if (!empty($formValues['bind_format']) && $formValues['format_id']) {
  234. $messageTemplate['pdf_format_id'] = $formValues['format_id'];
  235. }
  236. if (!empty($formValues['saveTemplate']) && $formValues['saveTemplate']) {
  237. $messageTemplate['msg_title'] = $formValues['saveTemplateName'];
  238. CRM_Core_BAO_MessageTemplate::add($messageTemplate);
  239. }
  240. if (!empty($formValues['updateTemplate']) && $formValues['template'] && $formValues['updateTemplate']) {
  241. $messageTemplate['id'] = $formValues['template'];
  242. unset($messageTemplate['msg_title']);
  243. CRM_Core_BAO_MessageTemplate::add($messageTemplate);
  244. }
  245. }
  246. elseif (CRM_Utils_Array::value('template', $formValues) > 0) {
  247. if (!empty($formValues['bind_format']) && $formValues['format_id']) {
  248. $query = "UPDATE civicrm_msg_template SET pdf_format_id = {$formValues['format_id']} WHERE id = {$formValues['template']}";
  249. }
  250. else {
  251. $query = "UPDATE civicrm_msg_template SET pdf_format_id = NULL WHERE id = {$formValues['template']}";
  252. }
  253. CRM_Core_DAO::executeQuery($query);
  254. $documentInfo = CRM_Core_BAO_File::getEntityFile('civicrm_msg_template', $formValues['template']);
  255. foreach ((array) $documentInfo as $info) {
  256. list($html_message, $formValues['document_type']) = CRM_Utils_PDF_Document::docReader($info['fullPath'], $info['mime_type']);
  257. $formValues['document_file_path'] = $info['fullPath'];
  258. }
  259. }
  260. // extract the content of uploaded document file
  261. elseif (!empty($formValues['document_file'])) {
  262. list($html_message, $formValues['document_type']) = CRM_Utils_PDF_Document::docReader($formValues['document_file']['name'], $formValues['document_file']['type']);
  263. $formValues['document_file_path'] = $formValues['document_file']['name'];
  264. }
  265. if (!empty($formValues['update_format'])) {
  266. $bao = new CRM_Core_BAO_PdfFormat();
  267. $bao->savePdfFormat($formValues, $formValues['format_id']);
  268. }
  269. return $html_message;
  270. }
  271. /**
  272. * @param $message
  273. */
  274. public static function formatMessage(&$message) {
  275. $newLineOperators = [
  276. 'p' => [
  277. 'oper' => '<p>',
  278. 'pattern' => '/<(\s+)?p(\s+)?>/m',
  279. ],
  280. 'br' => [
  281. 'oper' => '<br />',
  282. 'pattern' => '/<(\s+)?br(\s+)?\/>/m',
  283. ],
  284. ];
  285. $htmlMsg = preg_split($newLineOperators['p']['pattern'], $message);
  286. foreach ($htmlMsg as $k => & $m) {
  287. $messages = preg_split($newLineOperators['br']['pattern'], $m);
  288. foreach ($messages as $key => & $msg) {
  289. $msg = trim($msg);
  290. $matches = [];
  291. if (preg_match('/^(&nbsp;)+/', $msg, $matches)) {
  292. $spaceLen = strlen($matches[0]) / 6;
  293. $trimMsg = ltrim($msg, '&nbsp; ');
  294. $charLen = strlen($trimMsg);
  295. $totalLen = $charLen + $spaceLen;
  296. if ($totalLen > 100) {
  297. $spacesCount = 10;
  298. if ($spaceLen > 50) {
  299. $spacesCount = 20;
  300. }
  301. if ($charLen > 100) {
  302. $spacesCount = 1;
  303. }
  304. $msg = str_repeat('&nbsp;', $spacesCount) . $trimMsg;
  305. }
  306. }
  307. }
  308. $m = implode($newLineOperators['br']['oper'], $messages);
  309. }
  310. $message = implode($newLineOperators['p']['oper'], $htmlMsg);
  311. }
  312. }