Merge pull request #4726 from atif-shaikh/CRM-5039
[civicrm-core.git] / CRM / Contact / Form / Task / PDFLetterCommon.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * This class provides the common functionality for creating PDF letter for
38 * one or a group of contact ids.
39 */
40 class CRM_Contact_Form_Task_PDFLetterCommon {
41
42 /**
43 * Build all the data structures needed to build the form
44 *
45 * @param CRM_Core_Form $form
46 *
47 * @return void
48 * @access public
49 */
50 static function preProcess(&$form) {
51 $messageText = array();
52 $messageSubject = array();
53 $dao = new CRM_Core_BAO_MessageTemplate();
54 $dao->is_active = 1;
55 $dao->find();
56 while ($dao->fetch()) {
57 $messageText[$dao->id] = $dao->msg_text;
58 $messageSubject[$dao->id] = $dao->msg_subject;
59 }
60
61 $form->assign('message', $messageText);
62 $form->assign('messageSubject', $messageSubject);
63 CRM_Utils_System::setTitle('Create Printable Letters (PDF)');
64 }
65
66 /**
67 * @param CRM_Core_Form $form
68 * @param int $cid
69 */
70 static function preProcessSingle(&$form, $cid) {
71 $form->_contactIds = array($cid);
72 // put contact display name in title for single contact mode
73 CRM_Utils_System::setTitle(ts('Create Printable Letter (PDF) for %1', array(1 => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name'))));
74 }
75
76 /**
77 * Build the form object
78 *
79 * @var CRM_Core_Form $form
80 *
81 * @return void
82 */
83 static function buildQuickForm(&$form) {
84 // This form outputs a file so should never be submitted via ajax
85 $form->preventAjaxSubmit();
86
87 //Added for CRM-12682: Add activity subject and campaign fields
88 CRM_Campaign_BAO_Campaign::addCampaign($form);
89 $form->add(
90 'text',
91 'subject',
92 ts('Activity Subject'),
93 array('size' => 45, 'maxlength' => 255),
94 FALSE
95 );
96
97 $form->add('static', 'pdf_format_header', NULL, ts('Page Format: %1', array(1 => '<span class="pdf-format-header-label"></span>')));
98 $form->addSelect('format_id', array(
99 'label' => ts('Select Format'),
100 'placeholder' => ts('Default'),
101 'entity' => 'message_template',
102 'field' => 'pdf_format_id',
103 'option_url' => 'civicrm/admin/pdfFormats',
104 ));
105 $form->add(
106 'select',
107 'paper_size',
108 ts('Paper Size'),
109 array(0 => ts('- default -')) + CRM_Core_BAO_PaperSize::getList(TRUE),
110 FALSE,
111 array('onChange' => "selectPaper( this.value ); showUpdateFormatChkBox();")
112 );
113 $form->add('static', 'paper_dimensions', NULL, ts('Width x Height'));
114 $form->add(
115 'select',
116 'orientation',
117 ts('Orientation'),
118 CRM_Core_BAO_PdfFormat::getPageOrientations(),
119 FALSE,
120 array('onChange' => "updatePaperDimensions(); showUpdateFormatChkBox();")
121 );
122 $form->add(
123 'select',
124 'metric',
125 ts('Unit of Measure'),
126 CRM_Core_BAO_PdfFormat::getUnits(),
127 FALSE,
128 array('onChange' => "selectMetric( this.value );")
129 );
130 $form->add(
131 'text',
132 'margin_left',
133 ts('Left Margin'),
134 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
135 TRUE
136 );
137 $form->add(
138 'text',
139 'margin_right',
140 ts('Right Margin'),
141 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
142 TRUE
143 );
144 $form->add(
145 'text',
146 'margin_top',
147 ts('Top Margin'),
148 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
149 TRUE
150 );
151 $form->add(
152 'text',
153 'margin_bottom',
154 ts('Bottom Margin'),
155 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
156 TRUE
157 );
158
159 $config = CRM_Core_Config::singleton();
160 if ($config->wkhtmltopdfPath == false) {
161 $form->add(
162 'text',
163 'stationery',
164 ts('Stationery (relative path to PDF you wish to use as the background)'),
165 array('size' => 25, 'maxlength' => 900, 'onkeyup' => "showUpdateFormatChkBox();"),
166 FALSE
167 );
168 }
169 $form->add('checkbox', 'bind_format', ts('Always use this Page Format with the selected Template'));
170 $form->add('checkbox', 'update_format', ts('Update Page Format (this will affect all templates that use this format)'));
171
172 $form->assign('useThisPageFormat', ts('Always use this Page Format with the new template?'));
173 $form->assign('useSelectedPageFormat', ts('Should the new template always use the selected Page Format?'));
174 $form->assign('totalSelectedContacts', count($form->_contactIds));
175
176 CRM_Mailing_BAO_Mailing::commonLetterCompose($form);
177
178 $buttons = array();
179 if ($form->get('action') != CRM_Core_Action::VIEW) {
180 $buttons[] = array(
181 'type' => 'submit',
182 'name' => $form->_single ? ts('Make PDF') : ts('Make PDFs'),
183 'isDefault' => TRUE,
184 );
185 }
186 $buttons[] = array(
187 'type' => 'cancel',
188 'name' => $form->get('action') == CRM_Core_Action::VIEW ? ts('Done') : ts('Cancel'),
189 );
190 $form->addButtons($buttons);
191
192 $form->addFormRule(array('CRM_Contact_Form_Task_PDFLetterCommon', 'formRule'), $form);
193 }
194
195 /**
196 * Set default values
197 */
198 static function setDefaultValues() {
199 $defaultFormat = CRM_Core_BAO_PdfFormat::getDefaultValues();
200 $defaultFormat['format_id'] = $defaultFormat['id'];
201 return $defaultFormat;
202 }
203
204 /**
205 * Form rule
206 *
207 * @param array $fields the input form values
208 * @param array $dontCare
209 * @param array $self additional values form 'this'
210 *
211 * @return true if no errors, else array of errors
212 * @access public
213 *
214 */
215 static function formRule($fields, $dontCare, $self) {
216 $errors = array();
217 $template = CRM_Core_Smarty::singleton();
218
219 //Added for CRM-1393
220 if (!empty($fields['saveTemplate']) && empty($fields['saveTemplateName'])) {
221 $errors['saveTemplateName'] = ts("Enter name to save message template");
222 }
223 if (!is_numeric($fields['margin_left'])) {
224 $errors['margin_left'] = 'Margin must be numeric';
225 }
226 if (!is_numeric($fields['margin_right'])) {
227 $errors['margin_right'] = 'Margin must be numeric';
228 }
229 if (!is_numeric($fields['margin_top'])) {
230 $errors['margin_top'] = 'Margin must be numeric';
231 }
232 if (!is_numeric($fields['margin_bottom'])) {
233 $errors['margin_bottom'] = 'Margin must be numeric';
234 }
235 return empty($errors) ? TRUE : $errors;
236 }
237
238 /**
239 * Part of the post process which prepare and extract information from the template
240 *
241 * @access protected
242 *
243 * @param CRM_Core_Form $form
244 *
245 * @return array( $categories, $html_message, $messageToken, $returnProperties )
246 */
247 static protected function processMessageTemplate(&$form) {
248 $formValues = $form->controller->exportValues($form->getName());
249
250 // process message template
251 if (!empty($formValues['saveTemplate']) || !empty($formValues['updateTemplate'])) {
252 $messageTemplate = array(
253 'msg_text' => NULL,
254 'msg_html' => $formValues['html_message'],
255 'msg_subject' => NULL,
256 'is_active' => TRUE,
257 );
258
259 $messageTemplate['pdf_format_id'] = 'null';
260 if (!empty($formValues['bind_format']) && $formValues['format_id']) {
261 $messageTemplate['pdf_format_id'] = $formValues['format_id'];
262 }
263 if (!empty($formValues['saveTemplate']) && $formValues['saveTemplate']) {
264 $messageTemplate['msg_title'] = $formValues['saveTemplateName'];
265 CRM_Core_BAO_MessageTemplate::add($messageTemplate);
266 }
267
268 if (!empty($formValues['updateTemplate']) && $formValues['template'] && $formValues['updateTemplate']) {
269 $messageTemplate['id'] = $formValues['template'];
270
271 unset($messageTemplate['msg_title']);
272 CRM_Core_BAO_MessageTemplate::add($messageTemplate);
273 }
274 }
275 elseif (CRM_Utils_Array::value('template', $formValues) > 0) {
276 if (!empty($formValues['bind_format']) && $formValues['format_id']) {
277 $query = "UPDATE civicrm_msg_template SET pdf_format_id = {$formValues['format_id']} WHERE id = {$formValues['template']}";
278 }
279 else {
280 $query = "UPDATE civicrm_msg_template SET pdf_format_id = NULL WHERE id = {$formValues['template']}";
281 }
282 CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
283 }
284 if (!empty($formValues['update_format'])) {
285 $bao = new CRM_Core_BAO_PdfFormat();
286 $bao->savePdfFormat($formValues, $formValues['format_id']);
287 }
288
289 $html = array();
290
291 $tokens = array();
292 CRM_Utils_Hook::tokens($tokens);
293 $categories = array_keys($tokens);
294
295 $html_message = $formValues['html_message'];
296
297 //time being hack to strip '&nbsp;'
298 //from particular letter line, CRM-6798
299 self::formatMessage($html_message);
300
301 $messageToken = CRM_Utils_Token::getTokens($html_message);
302
303 $returnProperties = array();
304 if (isset($messageToken['contact'])) {
305 foreach ($messageToken['contact'] as $key => $value) {
306 $returnProperties[$value] = 1;
307 }
308 }
309
310 return array($formValues, $categories, $html_message, $messageToken, $returnProperties);
311 }
312
313 /**
314 * Process the form after the input has been submitted and validated
315 *
316 * @access public
317 *
318 * @param CRM_Core_Form $form
319 *
320 * @return void
321 */
322 static function postProcess(&$form) {
323 list($formValues, $categories, $html_message, $messageToken, $returnProperties) = self::processMessageTemplate($form);
324
325 $skipOnHold = isset($form->skipOnHold) ? $form->skipOnHold : FALSE;
326 $skipDeceased = isset($form->skipDeceased) ? $form->skipDeceased : TRUE;
327
328 foreach ($form->_contactIds as $item => $contactId) {
329 $params = array('contact_id' => $contactId);
330
331 list($contact) = CRM_Utils_Token::getTokenDetails($params,
332 $returnProperties,
333 $skipOnHold,
334 $skipDeceased,
335 NULL,
336 $messageToken,
337 'CRM_Contact_Form_Task_PDFLetterCommon'
338 );
339 if (civicrm_error($contact)) {
340 $notSent[] = $contactId;
341 continue;
342 }
343
344 $tokenHtml = CRM_Utils_Token::replaceContactTokens($html_message, $contact[$contactId], TRUE, $messageToken);
345 $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $contact[$contactId], $categories, TRUE);
346
347 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
348 $smarty = CRM_Core_Smarty::singleton();
349 // also add the contact tokens to the template
350 $smarty->assign_by_ref('contact', $contact);
351 $tokenHtml = $smarty->fetch("string:$tokenHtml");
352 }
353
354 $html[] = $tokenHtml;
355 }
356
357 self::createActivities($form, $html_message, $form->_contactIds);
358
359 CRM_Utils_PDF_Utils::html2pdf($html, "CiviLetter.pdf", FALSE, $formValues);
360
361 $form->postProcessHook();
362
363 CRM_Utils_System::civiExit(1);
364 }
365
366 /**
367 * @param CRM_Core_Form $form
368 * @param $html_message
369 * @param $contactIds
370 *
371 * @throws CRM_Core_Exception
372 */
373 static function createActivities($form, $html_message, $contactIds) {
374 //Added for CRM-12682: Add activity subject and campaign fields
375 $formValues = $form->controller->exportValues($form->getName());
376
377 $session = CRM_Core_Session::singleton();
378 $userID = $session->get('userID');
379 $activityTypeID = CRM_Core_OptionGroup::getValue(
380 'activity_type',
381 'Print PDF Letter',
382 'name'
383 );
384 $activityParams = array(
385 'subject' => $formValues['subject'],
386 'campaign_id' => CRM_Utils_Array::value('campaign_id', $formValues),
387 'source_contact_id' => $userID,
388 'activity_type_id' => $activityTypeID,
389 'activity_date_time' => date('YmdHis'),
390 'details' => $html_message,
391 );
392 if (!empty($form->_activityId)) {
393 $activityParams += array('id' => $form->_activityId);
394 }
395 if ($form->_cid) {
396 $activity = CRM_Activity_BAO_Activity::create($activityParams);
397 }
398 else {
399 // create Print PDF activity for each selected contact. CRM-6886
400 $activityIds = array();
401 foreach ($contactIds as $contactId) {
402 $activityID = CRM_Activity_BAO_Activity::create($activityParams);
403 $activityIds[$contactId] = $activityID->id;
404 }
405 }
406
407 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
408 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
409
410 //@todo why are we using $form->_contactIds here & contactIds above - need comment
411 foreach ($form->_contactIds as $contactId) {
412 $activityTargetParams = array(
413 'activity_id' => empty($activity->id) ? $activityIds[$contactId] : $activity->id,
414 'contact_id' => $contactId,
415 'record_type_id' => $targetID
416 );
417 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
418 }
419 }
420
421 /**
422 * @param $message
423 */
424 static function formatMessage(&$message) {
425 $newLineOperators = array(
426 'p' => array(
427 'oper' => '<p>',
428 'pattern' => '/<(\s+)?p(\s+)?>/m',
429 ),
430 'br' => array(
431 'oper' => '<br />',
432 'pattern' => '/<(\s+)?br(\s+)?\/>/m',
433 ),
434 );
435
436 $htmlMsg = preg_split($newLineOperators['p']['pattern'], $message);
437 foreach ($htmlMsg as $k => & $m) {
438 $messages = preg_split($newLineOperators['br']['pattern'], $m);
439 foreach ($messages as $key => & $msg) {
440 $msg = trim($msg);
441 $matches = array();
442 if (preg_match('/^(&nbsp;)+/', $msg, $matches)) {
443 $spaceLen = strlen($matches[0]) / 6;
444 $trimMsg = ltrim($msg, '&nbsp; ');
445 $charLen = strlen($trimMsg);
446 $totalLen = $charLen + $spaceLen;
447 if ($totalLen > 100) {
448 $spacesCount = 10;
449 if ($spaceLen > 50) {
450 $spacesCount = 20;
451 }
452 if ($charLen > 100) {
453 $spacesCount = 1;
454 }
455 $msg = str_repeat('&nbsp;', $spacesCount) . $trimMsg;
456 }
457 }
458 }
459 $m = implode($newLineOperators['br']['oper'], $messages);
460 }
461 $message = implode($newLineOperators['p']['oper'], $htmlMsg);
462 }
463 }
464