Merge remote-tracking branch 'upstream/4.5' into 4.5-master-2015-01-26-14-28-00
[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 */
49 public static function preProcess(&$form) {
50 $messageText = array();
51 $messageSubject = array();
52 $dao = new CRM_Core_BAO_MessageTemplate();
53 $dao->is_active = 1;
54 $dao->find();
55 while ($dao->fetch()) {
56 $messageText[$dao->id] = $dao->msg_text;
57 $messageSubject[$dao->id] = $dao->msg_subject;
58 }
59
60 $form->assign('message', $messageText);
61 $form->assign('messageSubject', $messageSubject);
62 CRM_Utils_System::setTitle('Create Printable Letters (PDF)');
63 }
64
65 /**
66 * @param CRM_Core_Form $form
67 * @param int $cid
68 */
69 public static function preProcessSingle(&$form, $cid) {
70 $form->_contactIds = array($cid);
71 // put contact display name in title for single contact mode
72 CRM_Utils_System::setTitle(ts('Create Printable Letter (PDF) for %1', array(1 => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid, 'display_name'))));
73 }
74
75 /**
76 * Build the form object
77 *
78 * @var CRM_Core_Form $form
79 *
80 * @return void
81 */
82 public static function buildQuickForm(&$form) {
83 // This form outputs a file so should never be submitted via ajax
84 $form->preventAjaxSubmit();
85
86 //Added for CRM-12682: Add activity subject and campaign fields
87 CRM_Campaign_BAO_Campaign::addCampaign($form);
88 $form->add(
89 'text',
90 'subject',
91 ts('Activity Subject'),
92 array('size' => 45, 'maxlength' => 255),
93 FALSE
94 );
95
96 $form->add('static', 'pdf_format_header', NULL, ts('Page Format: %1', array(1 => '<span class="pdf-format-header-label"></span>')));
97 $form->addSelect('format_id', array(
98 'label' => ts('Select Format'),
99 'placeholder' => ts('Default'),
100 'entity' => 'message_template',
101 'field' => 'pdf_format_id',
102 'option_url' => 'civicrm/admin/pdfFormats',
103 ));
104 $form->add(
105 'select',
106 'paper_size',
107 ts('Paper Size'),
108 array(0 => ts('- default -')) + CRM_Core_BAO_PaperSize::getList(TRUE),
109 FALSE,
110 array('onChange' => "selectPaper( this.value ); showUpdateFormatChkBox();")
111 );
112 $form->add('static', 'paper_dimensions', NULL, ts('Width x Height'));
113 $form->add(
114 'select',
115 'orientation',
116 ts('Orientation'),
117 CRM_Core_BAO_PdfFormat::getPageOrientations(),
118 FALSE,
119 array('onChange' => "updatePaperDimensions(); showUpdateFormatChkBox();")
120 );
121 $form->add(
122 'select',
123 'metric',
124 ts('Unit of Measure'),
125 CRM_Core_BAO_PdfFormat::getUnits(),
126 FALSE,
127 array('onChange' => "selectMetric( this.value );")
128 );
129 $form->add(
130 'text',
131 'margin_left',
132 ts('Left Margin'),
133 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
134 TRUE
135 );
136 $form->add(
137 'text',
138 'margin_right',
139 ts('Right Margin'),
140 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
141 TRUE
142 );
143 $form->add(
144 'text',
145 'margin_top',
146 ts('Top Margin'),
147 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
148 TRUE
149 );
150 $form->add(
151 'text',
152 'margin_bottom',
153 ts('Bottom Margin'),
154 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
155 TRUE
156 );
157
158 $config = CRM_Core_Config::singleton();
159 if ($config->wkhtmltopdfPath == FALSE) {
160 $form->add(
161 'text',
162 'stationery',
163 ts('Stationery (relative path to PDF you wish to use as the background)'),
164 array('size' => 25, 'maxlength' => 900, 'onkeyup' => "showUpdateFormatChkBox();"),
165 FALSE
166 );
167 }
168 $form->add('checkbox', 'bind_format', ts('Always use this Page Format with the selected Template'));
169 $form->add('checkbox', 'update_format', ts('Update Page Format (this will affect all templates that use this format)'));
170
171 $form->assign('useThisPageFormat', ts('Always use this Page Format with the new template?'));
172 $form->assign('useSelectedPageFormat', ts('Should the new template always use the selected Page Format?'));
173 $form->assign('totalSelectedContacts', count($form->_contactIds));
174
175 CRM_Mailing_BAO_Mailing::commonLetterCompose($form);
176
177 $buttons = array();
178 if ($form->get('action') != CRM_Core_Action::VIEW) {
179 $buttons[] = array(
180 'type' => 'submit',
181 'name' => $form->_single ? ts('Make PDF') : ts('Make PDFs'),
182 'isDefault' => TRUE,
183 );
184 }
185 $buttons[] = array(
186 'type' => 'cancel',
187 'name' => $form->get('action') == CRM_Core_Action::VIEW ? ts('Done') : ts('Cancel'),
188 );
189 $form->addButtons($buttons);
190
191 $form->addFormRule(array('CRM_Contact_Form_Task_PDFLetterCommon', 'formRule'), $form);
192 }
193
194 /**
195 * Set default values
196 */
197 public static function setDefaultValues() {
198 $defaultFormat = CRM_Core_BAO_PdfFormat::getDefaultValues();
199 $defaultFormat['format_id'] = $defaultFormat['id'];
200 return $defaultFormat;
201 }
202
203 /**
204 * Form rule
205 *
206 * @param array $fields
207 * The input form values.
208 * @param array $dontCare
209 * @param array $self
210 * Additional values form 'this'.
211 *
212 * @return bool
213 * TRUE if no errors, else array of errors.
214 */
215 public 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 *
242 * @param CRM_Core_Form $form
243 *
244 * @return array
245 * [$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 *
317 * @param CRM_Core_Form $form
318 *
319 * @return void
320 */
321 public static function postProcess(&$form) {
322 list($formValues, $categories, $html_message, $messageToken, $returnProperties) = self::processMessageTemplate($form);
323
324 $skipOnHold = isset($form->skipOnHold) ? $form->skipOnHold : FALSE;
325 $skipDeceased = isset($form->skipDeceased) ? $form->skipDeceased : TRUE;
326
327 foreach ($form->_contactIds as $item => $contactId) {
328 $params = array('contact_id' => $contactId);
329
330 list($contact) = CRM_Utils_Token::getTokenDetails($params,
331 $returnProperties,
332 $skipOnHold,
333 $skipDeceased,
334 NULL,
335 $messageToken,
336 'CRM_Contact_Form_Task_PDFLetterCommon'
337 );
338 if (civicrm_error($contact)) {
339 $notSent[] = $contactId;
340 continue;
341 }
342
343 $tokenHtml = CRM_Utils_Token::replaceContactTokens($html_message, $contact[$contactId], TRUE, $messageToken);
344 $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $contact[$contactId], $categories, TRUE);
345
346 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
347 $smarty = CRM_Core_Smarty::singleton();
348 // also add the contact tokens to the template
349 $smarty->assign_by_ref('contact', $contact);
350 $tokenHtml = $smarty->fetch("string:$tokenHtml");
351 }
352
353 $html[] = $tokenHtml;
354 }
355
356 self::createActivities($form, $html_message, $form->_contactIds);
357
358 CRM_Utils_PDF_Utils::html2pdf($html, "CiviLetter.pdf", FALSE, $formValues);
359
360 $form->postProcessHook();
361
362 CRM_Utils_System::civiExit(1);
363 }
364
365 /**
366 * @param CRM_Core_Form $form
367 * @param $html_message
368 * @param $contactIds
369 *
370 * @throws CRM_Core_Exception
371 */
372 public static function createActivities($form, $html_message, $contactIds) {
373 //Added for CRM-12682: Add activity subject and campaign fields
374 $formValues = $form->controller->exportValues($form->getName());
375
376 $session = CRM_Core_Session::singleton();
377 $userID = $session->get('userID');
378 $activityTypeID = CRM_Core_OptionGroup::getValue(
379 'activity_type',
380 'Print PDF Letter',
381 'name'
382 );
383 $activityParams = array(
384 'subject' => $formValues['subject'],
385 'campaign_id' => CRM_Utils_Array::value('campaign_id', $formValues),
386 'source_contact_id' => $userID,
387 'activity_type_id' => $activityTypeID,
388 'activity_date_time' => date('YmdHis'),
389 'details' => $html_message,
390 );
391 if (!empty($form->_activityId)) {
392 $activityParams += array('id' => $form->_activityId);
393 }
394 if ($form->_cid) {
395 $activity = CRM_Activity_BAO_Activity::create($activityParams);
396 }
397 else {
398 // create Print PDF activity for each selected contact. CRM-6886
399 $activityIds = array();
400 foreach ($contactIds as $contactId) {
401 $activityID = CRM_Activity_BAO_Activity::create($activityParams);
402 $activityIds[$contactId] = $activityID->id;
403 }
404 }
405
406 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
407 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
408
409 //@todo why are we using $form->_contactIds here & contactIds above - need comment
410 foreach ($form->_contactIds as $contactId) {
411 $activityTargetParams = array(
412 'activity_id' => empty($activity->id) ? $activityIds[$contactId] : $activity->id,
413 'contact_id' => $contactId,
414 'record_type_id' => $targetID,
415 );
416 CRM_Activity_BAO_ActivityContact::create($activityTargetParams);
417 }
418 }
419
420 /**
421 * @param $message
422 */
423 public static function formatMessage(&$message) {
424 $newLineOperators = array(
425 'p' => array(
426 'oper' => '<p>',
427 'pattern' => '/<(\s+)?p(\s+)?>/m',
428 ),
429 'br' => array(
430 'oper' => '<br />',
431 'pattern' => '/<(\s+)?br(\s+)?\/>/m',
432 ),
433 );
434
435 $htmlMsg = preg_split($newLineOperators['p']['pattern'], $message);
436 foreach ($htmlMsg as $k => & $m) {
437 $messages = preg_split($newLineOperators['br']['pattern'], $m);
438 foreach ($messages as $key => & $msg) {
439 $msg = trim($msg);
440 $matches = array();
441 if (preg_match('/^(&nbsp;)+/', $msg, $matches)) {
442 $spaceLen = strlen($matches[0]) / 6;
443 $trimMsg = ltrim($msg, '&nbsp; ');
444 $charLen = strlen($trimMsg);
445 $totalLen = $charLen + $spaceLen;
446 if ($totalLen > 100) {
447 $spacesCount = 10;
448 if ($spaceLen > 50) {
449 $spacesCount = 20;
450 }
451 if ($charLen > 100) {
452 $spacesCount = 1;
453 }
454 $msg = str_repeat('&nbsp;', $spacesCount) . $trimMsg;
455 }
456 }
457 }
458 $m = implode($newLineOperators['br']['oper'], $messages);
459 }
460 $message = implode($newLineOperators['p']['oper'], $htmlMsg);
461 }
462
463 }