3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * This class provides the common functionality for creating PDF letter for
38 * one or a group of contact ids.
40 class CRM_Contact_Form_Task_PDFLetterCommon
{
43 * Build all the data structures needed to build the form
45 * @param CRM_Core_Form $form
50 static function preProcess(&$form) {
51 $messageText = array();
52 $messageSubject = array();
53 $dao = new CRM_Core_BAO_MessageTemplate();
56 while ($dao->fetch()) {
57 $messageText[$dao->id
] = $dao->msg_text
;
58 $messageSubject[$dao->id
] = $dao->msg_subject
;
61 $form->assign('message', $messageText);
62 $form->assign('messageSubject', $messageSubject);
63 CRM_Utils_System
::setTitle('Create Printable Letters (PDF)');
67 * @param CRM_Core_Form $form
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'))));
77 * Build the form object
79 * @var CRM_Core_Form $form
83 static function buildQuickForm(&$form) {
84 // This form outputs a file so should never be submitted via ajax
85 $form->preventAjaxSubmit();
87 //Added for CRM-12682: Add activity subject and campaign fields
88 CRM_Campaign_BAO_Campaign
::addCampaign($form);
92 ts('Activity Subject'),
93 array('size' => 45, 'maxlength' => 255),
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',
109 array(0 => ts('- default -')) + CRM_Core_BAO_PaperSize
::getList(TRUE),
111 array('onChange' => "selectPaper( this.value ); showUpdateFormatChkBox();")
113 $form->add('static', 'paper_dimensions', NULL, ts('Width x Height'));
118 CRM_Core_BAO_PdfFormat
::getPageOrientations(),
120 array('onChange' => "updatePaperDimensions(); showUpdateFormatChkBox();")
125 ts('Unit of Measure'),
126 CRM_Core_BAO_PdfFormat
::getUnits(),
128 array('onChange' => "selectMetric( this.value );")
134 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
141 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
148 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
155 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
159 $config = CRM_Core_Config
::singleton();
160 if ($config->wkhtmltopdfPath
== false) {
164 ts('Stationery (relative path to PDF you wish to use as the background)'),
165 array('size' => 25, 'maxlength' => 900, 'onkeyup' => "showUpdateFormatChkBox();"),
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)'));
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
));
176 CRM_Mailing_BAO_Mailing
::commonLetterCompose($form);
179 if ($form->get('action') != CRM_Core_Action
::VIEW
) {
182 'name' => $form->_single ?
ts('Make PDF') : ts('Make PDFs'),
188 'name' => $form->get('action') == CRM_Core_Action
::VIEW ?
ts('Done') : ts('Cancel'),
190 $form->addButtons($buttons);
192 $form->addFormRule(array('CRM_Contact_Form_Task_PDFLetterCommon', 'formRule'), $form);
198 static function setDefaultValues() {
199 $defaultFormat = CRM_Core_BAO_PdfFormat
::getDefaultValues();
200 $defaultFormat['format_id'] = $defaultFormat['id'];
201 return $defaultFormat;
207 * @param array $fields the input form values
208 * @param array $dontCare
209 * @param array $self additional values form 'this'
211 * @return true if no errors, else array of errors
215 static function formRule($fields, $dontCare, $self) {
217 $template = CRM_Core_Smarty
::singleton();
220 if (!empty($fields['saveTemplate']) && empty($fields['saveTemplateName'])) {
221 $errors['saveTemplateName'] = ts("Enter name to save message template");
223 if (!is_numeric($fields['margin_left'])) {
224 $errors['margin_left'] = 'Margin must be numeric';
226 if (!is_numeric($fields['margin_right'])) {
227 $errors['margin_right'] = 'Margin must be numeric';
229 if (!is_numeric($fields['margin_top'])) {
230 $errors['margin_top'] = 'Margin must be numeric';
232 if (!is_numeric($fields['margin_bottom'])) {
233 $errors['margin_bottom'] = 'Margin must be numeric';
235 return empty($errors) ?
TRUE : $errors;
239 * Part of the post process which prepare and extract information from the template
243 * @param CRM_Core_Form $form
245 * @return array( $categories, $html_message, $messageToken, $returnProperties )
247 static protected function processMessageTemplate(&$form) {
248 $formValues = $form->controller
->exportValues($form->getName());
250 // process message template
251 if (!empty($formValues['saveTemplate']) ||
!empty($formValues['updateTemplate'])) {
252 $messageTemplate = array(
254 'msg_html' => $formValues['html_message'],
255 'msg_subject' => NULL,
259 $messageTemplate['pdf_format_id'] = 'null';
260 if (!empty($formValues['bind_format']) && $formValues['format_id']) {
261 $messageTemplate['pdf_format_id'] = $formValues['format_id'];
263 if (!empty($formValues['saveTemplate']) && $formValues['saveTemplate']) {
264 $messageTemplate['msg_title'] = $formValues['saveTemplateName'];
265 CRM_Core_BAO_MessageTemplate
::add($messageTemplate);
268 if (!empty($formValues['updateTemplate']) && $formValues['template'] && $formValues['updateTemplate']) {
269 $messageTemplate['id'] = $formValues['template'];
271 unset($messageTemplate['msg_title']);
272 CRM_Core_BAO_MessageTemplate
::add($messageTemplate);
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']}";
280 $query = "UPDATE civicrm_msg_template SET pdf_format_id = NULL WHERE id = {$formValues['template']}";
282 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
284 if (!empty($formValues['update_format'])) {
285 $bao = new CRM_Core_BAO_PdfFormat();
286 $bao->savePdfFormat($formValues, $formValues['format_id']);
292 CRM_Utils_Hook
::tokens($tokens);
293 $categories = array_keys($tokens);
295 $html_message = $formValues['html_message'];
297 //time being hack to strip ' '
298 //from particular letter line, CRM-6798
299 self
::formatMessage($html_message);
301 $messageToken = CRM_Utils_Token
::getTokens($html_message);
303 $returnProperties = array();
304 if (isset($messageToken['contact'])) {
305 foreach ($messageToken['contact'] as $key => $value) {
306 $returnProperties[$value] = 1;
310 return array($formValues, $categories, $html_message, $messageToken, $returnProperties);
314 * Process the form after the input has been submitted and validated
318 * @param CRM_Core_Form $form
322 static function postProcess(&$form) {
323 list($formValues, $categories, $html_message, $messageToken, $returnProperties) = self
::processMessageTemplate($form);
325 $skipOnHold = isset($form->skipOnHold
) ?
$form->skipOnHold
: FALSE;
326 $skipDeceased = isset($form->skipDeceased
) ?
$form->skipDeceased
: TRUE;
328 foreach ($form->_contactIds
as $item => $contactId) {
329 $params = array('contact_id' => $contactId);
331 list($contact) = CRM_Utils_Token
::getTokenDetails($params,
337 'CRM_Contact_Form_Task_PDFLetterCommon'
339 if (civicrm_error($contact)) {
340 $notSent[] = $contactId;
344 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html_message, $contact[$contactId], TRUE, $messageToken);
345 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $contact[$contactId], $categories, TRUE);
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");
354 $html[] = $tokenHtml;
357 self
::createActivities($form, $html_message, $form->_contactIds
);
359 CRM_Utils_PDF_Utils
::html2pdf($html, "CiviLetter.pdf", FALSE, $formValues);
361 $form->postProcessHook();
363 CRM_Utils_System
::civiExit(1);
367 * @param CRM_Core_Form $form
368 * @param $html_message
371 * @throws CRM_Core_Exception
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());
377 $session = CRM_Core_Session
::singleton();
378 $userID = $session->get('userID');
379 $activityTypeID = CRM_Core_OptionGroup
::getValue(
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,
392 if (!empty($form->_activityId
)) {
393 $activityParams +
= array('id' => $form->_activityId
);
396 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
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
;
407 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
408 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
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
417 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
424 static function formatMessage(&$message) {
425 $newLineOperators = array(
428 'pattern' => '/<(\s+)?p(\s+)?>/m',
432 'pattern' => '/<(\s+)?br(\s+)?\/>/m',
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) {
442 if (preg_match('/^( )+/', $msg, $matches)) {
443 $spaceLen = strlen($matches[0]) / 6;
444 $trimMsg = ltrim($msg, ' ');
445 $charLen = strlen($trimMsg);
446 $totalLen = $charLen +
$spaceLen;
447 if ($totalLen > 100) {
449 if ($spaceLen > 50) {
452 if ($charLen > 100) {
455 $msg = str_repeat(' ', $spacesCount) . $trimMsg;
459 $m = implode($newLineOperators['br']['oper'], $messages);
461 $message = implode($newLineOperators['p']['oper'], $htmlMsg);