Merge pull request #10171 from seamuslee001/CRM-20427
[civicrm-core.git] / CRM / Contact / Form / Task / PDFLetterCommon.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
6a488035
TO
32 */
33
34/**
424029e3 35 * This class provides the common functionality for creating PDF letter for one or a group of contact ids.
6a488035
TO
36 */
37class CRM_Contact_Form_Task_PDFLetterCommon {
38
cc144465
TO
39 /**
40 * @return array
41 * Array(string $machineName => string $label).
42 */
43 public static function getLoggingOptions() {
44 return array(
45 'none' => ts('Do not record'),
46 'multiple' => ts('Multiple activities (one per contact)'),
47 'combined' => ts('One combined activity'),
48 'combined-attached' => ts('One combined activity plus one file attachment'),
49 // 'multiple-attached' <== not worth the work
50 );
51 }
52
6a488035 53 /**
fe482240 54 * Build all the data structures needed to build the form.
6a488035 55 *
c490a46a 56 * @param CRM_Core_Form $form
6a488035 57 */
00be9182 58 public static function preProcess(&$form) {
353ffa53 59 $messageText = array();
6a488035 60 $messageSubject = array();
353ffa53 61 $dao = new CRM_Core_BAO_MessageTemplate();
6a488035
TO
62 $dao->is_active = 1;
63 $dao->find();
64 while ($dao->fetch()) {
65 $messageText[$dao->id] = $dao->msg_text;
66 $messageSubject[$dao->id] = $dao->msg_subject;
67 }
68
69 $form->assign('message', $messageText);
70 $form->assign('messageSubject', $messageSubject);
cd095eae 71 CRM_Utils_System::setTitle('Print/Merge Document');
6a488035
TO
72 }
73
86538308 74 /**
c490a46a 75 * @param CRM_Core_Form $form
100fef9d 76 * @param int $cid
86538308 77 */
00be9182 78 public static function preProcessSingle(&$form, $cid) {
6a488035
TO
79 $form->_contactIds = array($cid);
80 // put contact display name in title for single contact mode
cd095eae 81 CRM_Utils_System::setTitle(ts('Print/Merge Document for %1', array(1 => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name'))));
6a488035
TO
82 }
83
84 /**
fe482240 85 * Build the form object.
6a488035 86 *
cae80d9f 87 * @var CRM_Core_Form $form
6a488035 88 */
00be9182 89 public static function buildQuickForm(&$form) {
cae80d9f
CW
90 // This form outputs a file so should never be submitted via ajax
91 $form->preventAjaxSubmit();
92
4c71ccb4
RN
93 //Added for CRM-12682: Add activity subject and campaign fields
94 CRM_Campaign_BAO_Campaign::addCampaign($form);
95 $form->add(
96 'text',
97 'subject',
98 ts('Activity Subject'),
99 array('size' => 45, 'maxlength' => 255),
100 FALSE
101 );
102
a7916823
CW
103 $form->add('static', 'pdf_format_header', NULL, ts('Page Format: %1', array(1 => '<span class="pdf-format-header-label"></span>')));
104 $form->addSelect('format_id', array(
105 'label' => ts('Select Format'),
106 'placeholder' => ts('Default'),
107 'entity' => 'message_template',
108 'field' => 'pdf_format_id',
109 'option_url' => 'civicrm/admin/pdfFormats',
110 ));
ed106721
DL
111 $form->add(
112 'select',
113 'paper_size',
114 ts('Paper Size'),
115 array(0 => ts('- default -')) + CRM_Core_BAO_PaperSize::getList(TRUE),
116 FALSE,
6a488035
TO
117 array('onChange' => "selectPaper( this.value ); showUpdateFormatChkBox();")
118 );
119 $form->add('static', 'paper_dimensions', NULL, ts('Width x Height'));
ed106721
DL
120 $form->add(
121 'select',
122 'orientation',
123 ts('Orientation'),
124 CRM_Core_BAO_PdfFormat::getPageOrientations(),
125 FALSE,
6a488035
TO
126 array('onChange' => "updatePaperDimensions(); showUpdateFormatChkBox();")
127 );
ed106721
DL
128 $form->add(
129 'select',
130 'metric',
131 ts('Unit of Measure'),
132 CRM_Core_BAO_PdfFormat::getUnits(),
133 FALSE,
6a488035
TO
134 array('onChange' => "selectMetric( this.value );")
135 );
ed106721
DL
136 $form->add(
137 'text',
138 'margin_left',
139 ts('Left Margin'),
140 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
141 TRUE
6a488035 142 );
ed106721
DL
143 $form->add(
144 'text',
145 'margin_right',
146 ts('Right Margin'),
147 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
148 TRUE
6a488035 149 );
ed106721
DL
150 $form->add(
151 'text',
152 'margin_top',
153 ts('Top Margin'),
154 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
155 TRUE
6a488035 156 );
ed106721
DL
157 $form->add(
158 'text',
159 'margin_bottom',
160 ts('Bottom Margin'),
161 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
162 TRUE
6a488035 163 );
bdfa67c3 164
165 $config = CRM_Core_Config::singleton();
828659cf 166 /** CRM-15883 Suppressing Stationery path field until we switch from DOMPDF to a library that supports it.
ab8a593e 167 if ($config->wkhtmltopdfPath == FALSE) {
828659cf
DG
168 $form->add(
169 'text',
170 'stationery',
171 ts('Stationery (relative path to PDF you wish to use as the background)'),
172 array('size' => 25, 'maxlength' => 900, 'onkeyup' => "showUpdateFormatChkBox();"),
173 FALSE
174 );
bdfa67c3 175 }
828659cf 176 */
6a488035
TO
177 $form->add('checkbox', 'bind_format', ts('Always use this Page Format with the selected Template'));
178 $form->add('checkbox', 'update_format', ts('Update Page Format (this will affect all templates that use this format)'));
179
180 $form->assign('useThisPageFormat', ts('Always use this Page Format with the new template?'));
181 $form->assign('useSelectedPageFormat', ts('Should the new template always use the selected Page Format?'));
182 $form->assign('totalSelectedContacts', count($form->_contactIds));
183
0aeb5a1e
CW
184 $form->add('select', 'document_type', ts('Document Type'), CRM_Core_SelectValues::documentFormat());
185
8d63890e 186 $documentTypes = implode(',', CRM_Core_SelectValues::documentApplicationType());
1f46c1b9 187 $form->addElement('file', "document_file", 'Upload Document', 'size=30 maxlength=255 accept="' . $documentTypes . '"');
8d63890e 188 $form->addUploadElement("document_file");
189
36d27c19 190 CRM_Mailing_BAO_Mailing::commonCompose($form);
6a488035 191
fc942baa
CW
192 $buttons = array();
193 if ($form->get('action') != CRM_Core_Action::VIEW) {
a37ec997 194 $buttons[] = array(
8d63890e 195 'type' => 'upload',
cd095eae 196 'name' => ts('Download Document'),
188bad99 197 'isDefault' => TRUE,
0aeb5a1e 198 'icon' => 'fa-download',
a37ec997 199 );
fc942baa
CW
200 $buttons[] = array(
201 'type' => 'submit',
188bad99
CW
202 'name' => ts('Preview'),
203 'subName' => 'preview',
0291a521 204 'icon' => 'fa-search',
188bad99 205 'isDefault' => FALSE,
6a488035 206 );
6a488035 207 }
fc942baa
CW
208 $buttons[] = array(
209 'type' => 'cancel',
210 'name' => $form->get('action') == CRM_Core_Action::VIEW ? ts('Done') : ts('Cancel'),
211 );
212 $form->addButtons($buttons);
6a488035
TO
213
214 $form->addFormRule(array('CRM_Contact_Form_Task_PDFLetterCommon', 'formRule'), $form);
215 }
216
217 /**
fe482240 218 * Set default values.
6a488035 219 */
00be9182 220 public static function setDefaultValues() {
6a488035
TO
221 $defaultFormat = CRM_Core_BAO_PdfFormat::getDefaultValues();
222 $defaultFormat['format_id'] = $defaultFormat['id'];
223 return $defaultFormat;
224 }
225
226 /**
fe482240 227 * Form rule.
6a488035 228 *
77c5b619
TO
229 * @param array $fields
230 * The input form values.
100e363e 231 * @param array $files
77c5b619
TO
232 * @param array $self
233 * Additional values form 'this'.
6a488035 234 *
4eeb9a5b
TO
235 * @return bool
236 * TRUE if no errors, else array of errors.
6a488035 237 */
100e363e 238 public static function formRule($fields, $files, $self) {
6a488035
TO
239 $errors = array();
240 $template = CRM_Core_Smarty::singleton();
241
100e363e 242 // If user uploads non-document file other than odt/docx
243 if (empty($fields['template']) &&
244 !empty($files['document_file']['tmp_name']) &&
245 array_search($files['document_file']['type'], CRM_Core_SelectValues::documentApplicationType()) == NULL
246 ) {
247 $errors['document_file'] = ts('Invalid document file format');
248 }
6a488035 249 //Added for CRM-1393
a7488080 250 if (!empty($fields['saveTemplate']) && empty($fields['saveTemplateName'])) {
6a488035
TO
251 $errors['saveTemplateName'] = ts("Enter name to save message template");
252 }
253 if (!is_numeric($fields['margin_left'])) {
254 $errors['margin_left'] = 'Margin must be numeric';
255 }
256 if (!is_numeric($fields['margin_right'])) {
257 $errors['margin_right'] = 'Margin must be numeric';
258 }
259 if (!is_numeric($fields['margin_top'])) {
260 $errors['margin_top'] = 'Margin must be numeric';
261 }
262 if (!is_numeric($fields['margin_bottom'])) {
263 $errors['margin_bottom'] = 'Margin must be numeric';
264 }
265 return empty($errors) ? TRUE : $errors;
266 }
267
268 /**
fe482240 269 * Part of the post process which prepare and extract information from the template.
6a488035 270 *
6a488035 271 *
2bd6b6cf 272 * @param array $formValues
dbddfb08 273 *
72b3a70c
CW
274 * @return array
275 * [$categories, $html_message, $messageToken, $returnProperties]
6a488035 276 */
2bd6b6cf 277 public static function processMessageTemplate($formValues) {
278 $html_message = CRM_Utils_Array::value('html_message', $formValues);
04a76231 279
6a488035 280 // process message template
8cc574cf 281 if (!empty($formValues['saveTemplate']) || !empty($formValues['updateTemplate'])) {
6a488035
TO
282 $messageTemplate = array(
283 'msg_text' => NULL,
284 'msg_html' => $formValues['html_message'],
285 'msg_subject' => NULL,
286 'is_active' => TRUE,
287 );
288
289 $messageTemplate['pdf_format_id'] = 'null';
a7916823 290 if (!empty($formValues['bind_format']) && $formValues['format_id']) {
6a488035
TO
291 $messageTemplate['pdf_format_id'] = $formValues['format_id'];
292 }
a7488080 293 if (!empty($formValues['saveTemplate']) && $formValues['saveTemplate']) {
6a488035 294 $messageTemplate['msg_title'] = $formValues['saveTemplateName'];
c6327d7d 295 CRM_Core_BAO_MessageTemplate::add($messageTemplate);
6a488035
TO
296 }
297
a7488080 298 if (!empty($formValues['updateTemplate']) && $formValues['template'] && $formValues['updateTemplate']) {
6a488035
TO
299 $messageTemplate['id'] = $formValues['template'];
300
301 unset($messageTemplate['msg_title']);
c6327d7d 302 CRM_Core_BAO_MessageTemplate::add($messageTemplate);
6a488035
TO
303 }
304 }
305 elseif (CRM_Utils_Array::value('template', $formValues) > 0) {
a7916823 306 if (!empty($formValues['bind_format']) && $formValues['format_id']) {
6a488035
TO
307 $query = "UPDATE civicrm_msg_template SET pdf_format_id = {$formValues['format_id']} WHERE id = {$formValues['template']}";
308 }
309 else {
310 $query = "UPDATE civicrm_msg_template SET pdf_format_id = NULL WHERE id = {$formValues['template']}";
311 }
33621c4f 312 CRM_Core_DAO::executeQuery($query);
04a76231 313
314 $documentInfo = CRM_Core_BAO_File::getEntityFile('civicrm_msg_template', $formValues['template']);
315 foreach ((array) $documentInfo as $info) {
9cbcd63f 316 list($html_message, $formValues['document_type']) = CRM_Utils_PDF_Document::docReader($info['fullPath'], $info['mime_type']);
ad7fdc34 317 $formValues['document_file_path'] = $info['fullPath'];
04a76231 318 }
6a488035 319 }
ad7fdc34 320 // extract the content of uploaded document file
321 elseif (!empty($formValues['document_file'])) {
9cbcd63f 322 list($html_message, $formValues['document_type']) = CRM_Utils_PDF_Document::docReader($formValues['document_file']['name'], $formValues['document_file']['type']);
ad7fdc34 323 $formValues['document_file_path'] = $formValues['document_file']['name'];
324 }
325
a7488080 326 if (!empty($formValues['update_format'])) {
6a488035
TO
327 $bao = new CRM_Core_BAO_PdfFormat();
328 $bao->savePdfFormat($formValues, $formValues['format_id']);
329 }
330
6a488035
TO
331 $tokens = array();
332 CRM_Utils_Hook::tokens($tokens);
333 $categories = array_keys($tokens);
334
6a488035
TO
335 //time being hack to strip '&nbsp;'
336 //from particular letter line, CRM-6798
337 self::formatMessage($html_message);
338
339 $messageToken = CRM_Utils_Token::getTokens($html_message);
340
341 $returnProperties = array();
342 if (isset($messageToken['contact'])) {
343 foreach ($messageToken['contact'] as $key => $value) {
344 $returnProperties[$value] = 1;
345 }
346 }
347
348 return array($formValues, $categories, $html_message, $messageToken, $returnProperties);
349 }
350
351 /**
fe482240 352 * Process the form after the input has been submitted and validated.
6a488035 353 *
c490a46a 354 * @param CRM_Core_Form $form
6a488035 355 */
00be9182 356 public static function postProcess(&$form) {
2bd6b6cf 357 $formValues = $form->controller->exportValues($form->getName());
358 list($formValues, $categories, $html_message, $messageToken, $returnProperties) = self::processMessageTemplate($formValues);
a37ec997 359 $buttonName = $form->controller->getButtonName();
6a488035
TO
360 $skipOnHold = isset($form->skipOnHold) ? $form->skipOnHold : FALSE;
361 $skipDeceased = isset($form->skipDeceased) ? $form->skipDeceased : TRUE;
3c48a60c 362 $html = $activityIds = array();
ad7fdc34 363
364 // CRM-16725 Skip creation of activities if user is previewing their PDF letter(s)
0875bb9b 365 if ($buttonName == '_qf_PDF_upload') {
3c48a60c 366 $activityIds = self::createActivities($form, $html_message, $form->_contactIds);
ad7fdc34 367 }
368
369 if (!empty($formValues['document_file_path'])) {
9eae09f1 370 list($html_message, $zip) = CRM_Utils_PDF_Document::unzipDoc($formValues['document_file_path'], $formValues['document_type']);
ad7fdc34 371 }
6a488035
TO
372
373 foreach ($form->_contactIds as $item => $contactId) {
8ffa3b7c 374 $caseId = NULL;
6a488035
TO
375 $params = array('contact_id' => $contactId);
376
377 list($contact) = CRM_Utils_Token::getTokenDetails($params,
378 $returnProperties,
379 $skipOnHold,
380 $skipDeceased,
381 NULL,
382 $messageToken,
383 'CRM_Contact_Form_Task_PDFLetterCommon'
384 );
2c8a6e63 385
6a488035
TO
386 if (civicrm_error($contact)) {
387 $notSent[] = $contactId;
388 continue;
389 }
390
391 $tokenHtml = CRM_Utils_Token::replaceContactTokens($html_message, $contact[$contactId], TRUE, $messageToken);
07945b3c 392 if (!empty($form->_caseId)) {
8ffa3b7c 393 $caseId = $form->_caseId;
394 }
395 if (empty($caseId) && !empty($form->_caseIds[$item])) {
396 $caseId = $form->_caseIds[$item];
397 }
398 if ($caseId) {
399 $tokenHtml = CRM_Utils_Token::replaceCaseTokens($caseId, $tokenHtml, $messageToken);
07945b3c 400 }
6a488035
TO
401 $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $contact[$contactId], $categories, TRUE);
402
403 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
404 $smarty = CRM_Core_Smarty::singleton();
405 // also add the contact tokens to the template
406 $smarty->assign_by_ref('contact', $contact);
407 $tokenHtml = $smarty->fetch("string:$tokenHtml");
408 }
409
410 $html[] = $tokenHtml;
411 }
412
38faa439
TO
413 $tee = NULL;
414 if (Civi::settings()->get('recordGeneratedLetters') === 'combined-attached') {
bdac10d8
TO
415 if (count($activityIds) !== 1) {
416 throw new CRM_Core_Exception("When recordGeneratedLetters=combined-attached, there should only be one activity.");
417 }
38faa439 418 $tee = CRM_Utils_ConsoleTee::create()->start();
3c48a60c
TO
419 }
420
0aeb5a1e 421 $type = $formValues['document_type'];
3c48a60c 422 $mimeType = self::getMimeType($type);
3ed92c14 423 // ^^ Useful side-effect: consistently throws error for unrecognized types.
0aeb5a1e
CW
424
425 if ($type == 'pdf') {
3c48a60c
TO
426 $fileName = "CiviLetter.$type";
427 CRM_Utils_PDF_Utils::html2pdf($html, $fileName, FALSE, $formValues);
0aeb5a1e 428 }
ad7fdc34 429 elseif (!empty($formValues['document_file_path'])) {
63c8a9ba
TO
430 $fileName = pathinfo($formValues['document_file_path'], PATHINFO_FILENAME) . '.' . $type;
431 CRM_Utils_PDF_Document::printDocuments($html, $fileName, $type, $zip);
ad7fdc34 432 }
0aeb5a1e 433 else {
3c48a60c
TO
434 $fileName = "CiviLetter.$type";
435 CRM_Utils_PDF_Document::html2doc($html, $fileName, $formValues);
436 }
437
38faa439
TO
438 if ($tee) {
439 $tee->stop();
440 $content = file_get_contents($tee->getFileName(), NULL, NULL, NULL, 5);
3c48a60c
TO
441 if (empty($content)) {
442 throw new \CRM_Core_Exception("Failed to capture document content (type=$type)!");
443 }
444 foreach ($activityIds as $activityId) {
445 civicrm_api3('Attachment', 'create', array(
446 'entity_table' => 'civicrm_activity',
447 'entity_id' => $activityId,
448 'name' => $fileName,
449 'mime_type' => $mimeType,
450 'options' => array(
38faa439 451 'move-file' => $tee->getFileName(),
3c48a60c
TO
452 ),
453 ));
454 }
0aeb5a1e 455 }
6a488035
TO
456
457 $form->postProcessHook();
458
459 CRM_Utils_System::civiExit(1);
460 }
461
86538308 462 /**
c490a46a 463 * @param CRM_Core_Form $form
818b4373
TO
464 * @param string $html_message
465 * @param array $contactIds
466 * @return array
467 * List of activity IDs.
468 * There may be 1 or more, depending on the system-settings
469 * and use-case.
86538308
EM
470 *
471 * @throws CRM_Core_Exception
472 */
00be9182 473 public static function createActivities($form, $html_message, $contactIds) {
4c71ccb4 474 //Added for CRM-12682: Add activity subject and campaign fields
353ffa53 475 $formValues = $form->controller->exportValues($form->getName());
6a488035 476
353ffa53
TO
477 $session = CRM_Core_Session::singleton();
478 $userID = $session->get('userID');
1d85d241
DL
479 $activityTypeID = CRM_Core_OptionGroup::getValue(
480 'activity_type',
6a488035
TO
481 'Print PDF Letter',
482 'name'
483 );
484 $activityParams = array(
4c71ccb4 485 'subject' => $formValues['subject'],
85d25c8f 486 'campaign_id' => CRM_Utils_Array::value('campaign_id', $formValues),
6a488035
TO
487 'source_contact_id' => $userID,
488 'activity_type_id' => $activityTypeID,
489 'activity_date_time' => date('YmdHis'),
490 'details' => $html_message,
491 );
492 if (!empty($form->_activityId)) {
493 $activityParams += array('id' => $form->_activityId);
494 }
818b4373
TO
495
496 // This seems silly, but the old behavior was to first check `_cid`
497 // and then use the provided `$contactIds`. Probably not even necessary,
498 // but difficult to audit.
499 $contactIds = $form->_cid ? array($form->_cid) : $contactIds;
6a488035 500
818b4373
TO
501 $activityIds = array();
502 switch (Civi::settings()->get('recordGeneratedLetters')) {
503 case 'none':
504 return array();
505
506 case 'multiple':
507 // One activity per contact.
508 foreach ($contactIds as $contactId) {
6d3827cb
TO
509 $fullParams = array(
510 'target_contact_id' => $contactId,
511 ) + $activityParams;
512 $activity = CRM_Activity_BAO_Activity::create($fullParams);
818b4373 513 $activityIds[$contactId] = $activity->id;
818b4373
TO
514 }
515
516 break;
517
518 case 'combined':
519 case 'combined-attached':
520 // One activity with all contacts.
6d3827cb
TO
521 $fullParams = array(
522 'target_contact_id' => $contactIds,
523 ) + $activityParams;
524 $activity = CRM_Activity_BAO_Activity::create($fullParams);
818b4373 525 $activityIds[] = $activity->id;
818b4373
TO
526 break;
527
528 default:
529 throw new CRM_Core_Exception("Unrecognized option in recordGeneratedLetters: " . Civi::settings()->get('recordGeneratedLetters'));
6a488035 530 }
818b4373
TO
531
532 if (!empty($form->_caseId)) {
533 foreach ($activityIds as $activityId) {
534 $caseActivityParams = array('activity_id' => $activityId, 'case_id' => $form->_caseId);
535 CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
536 }
537 }
538
539 return $activityIds;
6a488035
TO
540 }
541
86538308
EM
542 /**
543 * @param $message
544 */
00be9182 545 public static function formatMessage(&$message) {
6a488035
TO
546 $newLineOperators = array(
547 'p' => array(
548 'oper' => '<p>',
549 'pattern' => '/<(\s+)?p(\s+)?>/m',
550 ),
551 'br' => array(
552 'oper' => '<br />',
553 'pattern' => '/<(\s+)?br(\s+)?\/>/m',
554 ),
555 );
556
557 $htmlMsg = preg_split($newLineOperators['p']['pattern'], $message);
558 foreach ($htmlMsg as $k => & $m) {
559 $messages = preg_split($newLineOperators['br']['pattern'], $m);
560 foreach ($messages as $key => & $msg) {
561 $msg = trim($msg);
562 $matches = array();
563 if (preg_match('/^(&nbsp;)+/', $msg, $matches)) {
564 $spaceLen = strlen($matches[0]) / 6;
353ffa53
TO
565 $trimMsg = ltrim($msg, '&nbsp; ');
566 $charLen = strlen($trimMsg);
6a488035
TO
567 $totalLen = $charLen + $spaceLen;
568 if ($totalLen > 100) {
569 $spacesCount = 10;
570 if ($spaceLen > 50) {
571 $spacesCount = 20;
572 }
573 if ($charLen > 100) {
574 $spacesCount = 1;
575 }
576 $msg = str_repeat('&nbsp;', $spacesCount) . $trimMsg;
577 }
578 }
579 }
580 $m = implode($newLineOperators['br']['oper'], $messages);
581 }
582 $message = implode($newLineOperators['p']['oper'], $htmlMsg);
583 }
96025800 584
3c48a60c
TO
585 /**
586 * Convert from a vague-type/file-extension to mime-type.
587 *
588 * @param string $type
589 * @return string
590 * @throws \CRM_Core_Exception
591 */
592 private static function getMimeType($type) {
593 $mimeTypes = array(
4b54b8bb 594 'pdf' => 'application/pdf',
3c48a60c
TO
595 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
596 'odt' => 'application/vnd.oasis.opendocument.text',
597 'html' => 'text/html',
598 );
599 if (isset($mimeTypes[$type])) {
600 return $mimeTypes[$type];
601 }
602 else {
603 throw new \CRM_Core_Exception("Cannot determine mime type");
604 }
605 }
606
6a488035 607}