3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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
48 static function preProcess(&$form) {
49 $messageText = array();
50 $messageSubject = array();
51 $dao = new CRM_Core_BAO_MessageTemplates();
54 while ($dao->fetch()) {
55 $messageText[$dao->id
] = $dao->msg_text
;
56 $messageSubject[$dao->id
] = $dao->msg_subject
;
59 $form->assign('message', $messageText);
60 $form->assign('messageSubject', $messageSubject);
63 static function preProcessSingle(&$form, $cid) {
64 $form->_contactIds
= array($cid);
65 // put contact display name in title for single contact mode
66 CRM_Contact_Page_View
::setTitle($cid);
76 static function buildQuickForm(&$form) {
77 $form->add('static', 'pdf_format_header', NULL, ts('Page Format'));
82 array(0 => ts('- default -')) + CRM_Core_BAO_PdfFormat
::getList(TRUE),
84 array('onChange' => "selectFormat( this.value, false );")
90 array(0 => ts('- default -')) + CRM_Core_BAO_PaperSize
::getList(TRUE),
92 array('onChange' => "selectPaper( this.value ); showUpdateFormatChkBox();")
94 $form->add('static', 'paper_dimensions', NULL, ts('Width x Height'));
99 CRM_Core_BAO_PdfFormat
::getPageOrientations(),
101 array('onChange' => "updatePaperDimensions(); showUpdateFormatChkBox();")
106 ts('Unit of Measure'),
107 CRM_Core_BAO_PdfFormat
::getUnits(),
109 array('onChange' => "selectMetric( this.value );")
115 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
122 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
129 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
136 array('size' => 8, 'maxlength' => 8, 'onkeyup' => "showUpdateFormatChkBox();"),
139 $form->add('checkbox', 'bind_format', ts('Always use this Page Format with the selected Template'));
140 $form->add('checkbox', 'update_format', ts('Update Page Format (this will affect all templates that use this format)'));
142 $form->assign('useThisPageFormat', ts('Always use this Page Format with the new template?'));
143 $form->assign('useSelectedPageFormat', ts('Should the new template always use the selected Page Format?'));
144 $form->assign('totalSelectedContacts', count($form->_contactIds
));
146 CRM_Mailing_BAO_Mailing
::commonLetterCompose($form);
148 if ($form->_single
) {
149 $cancelURL = CRM_Utils_System
::url(
150 'civicrm/contact/view',
151 "reset=1&cid={$form->_cid}&selectedChild=activity",
156 if ($form->get('action') == CRM_Core_Action
::VIEW
) {
157 $form->addButtons(array(
160 'name' => ts('Done'),
161 'js' => array('onclick' => "location.href='{$cancelURL}'; return false;"),
167 $form->addButtons(array(
170 'name' => ts('Make PDF Letter'),
175 'name' => ts('Done'),
176 'js' => array('onclick' => "location.href='{$cancelURL}'; return false;"),
183 $form->addDefaultButtons(ts('Make PDF Letters'));
186 $form->addFormRule(array('CRM_Contact_Form_Task_PDFLetterCommon', 'formRule'), $form);
192 static function setDefaultValues() {
193 $defaultFormat = CRM_Core_BAO_PdfFormat
::getDefaultValues();
194 $defaultFormat['format_id'] = $defaultFormat['id'];
195 return $defaultFormat;
201 * @param array $fields the input form values
202 * @param array $dontCare
203 * @param array $self additional values form 'this'
205 * @return true if no errors, else array of errors
209 static function formRule($fields, $dontCare, $self) {
211 $template = CRM_Core_Smarty
::singleton();
214 if (CRM_Utils_Array
::value('saveTemplate', $fields) && empty($fields['saveTemplateName'])) {
215 $errors['saveTemplateName'] = ts("Enter name to save message template");
217 if (!is_numeric($fields['margin_left'])) {
218 $errors['margin_left'] = 'Margin must be numeric';
220 if (!is_numeric($fields['margin_right'])) {
221 $errors['margin_right'] = 'Margin must be numeric';
223 if (!is_numeric($fields['margin_top'])) {
224 $errors['margin_top'] = 'Margin must be numeric';
226 if (!is_numeric($fields['margin_bottom'])) {
227 $errors['margin_bottom'] = 'Margin must be numeric';
229 return empty($errors) ?
TRUE : $errors;
233 * part of the post process which prepare and extract information from the template
237 * @return array( $categories, $html_message, $messageToken, $returnProperties )
239 static protected function processMessageTemplate(&$form) {
240 $formValues = $form->controller
->exportValues($form->getName());
242 // process message template
243 if (CRM_Utils_Array
::value('saveTemplate', $formValues) || CRM_Utils_Array
::value('updateTemplate', $formValues)) {
244 $messageTemplate = array(
246 'msg_html' => $formValues['html_message'],
247 'msg_subject' => NULL,
251 $messageTemplate['pdf_format_id'] = 'null';
252 if (CRM_Utils_Array
::value('bind_format', $formValues) && $formValues['format_id'] > 0) {
253 $messageTemplate['pdf_format_id'] = $formValues['format_id'];
255 if (CRM_Utils_Array
::value('saveTemplate', $formValues) && $formValues['saveTemplate']) {
256 $messageTemplate['msg_title'] = $formValues['saveTemplateName'];
257 CRM_Core_BAO_MessageTemplates
::add($messageTemplate);
260 if (CRM_Utils_Array
::value('updateTemplate', $formValues) && $formValues['template'] && $formValues['updateTemplate']) {
261 $messageTemplate['id'] = $formValues['template'];
263 unset($messageTemplate['msg_title']);
264 CRM_Core_BAO_MessageTemplates
::add($messageTemplate);
267 elseif (CRM_Utils_Array
::value('template', $formValues) > 0) {
268 if (CRM_Utils_Array
::value('bind_format', $formValues) && $formValues['format_id'] > 0) {
269 $query = "UPDATE civicrm_msg_template SET pdf_format_id = {$formValues['format_id']} WHERE id = {$formValues['template']}";
272 $query = "UPDATE civicrm_msg_template SET pdf_format_id = NULL WHERE id = {$formValues['template']}";
274 CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
276 if (CRM_Utils_Array
::value('update_format', $formValues)) {
277 $bao = new CRM_Core_BAO_PdfFormat();
278 $bao->savePdfFormat($formValues, $formValues['format_id']);
284 CRM_Utils_Hook
::tokens($tokens);
285 $categories = array_keys($tokens);
287 $html_message = $formValues['html_message'];
289 //time being hack to strip ' '
290 //from particular letter line, CRM-6798
291 self
::formatMessage($html_message);
293 $messageToken = CRM_Utils_Token
::getTokens($html_message);
295 $returnProperties = array();
296 if (isset($messageToken['contact'])) {
297 foreach ($messageToken['contact'] as $key => $value) {
298 $returnProperties[$value] = 1;
302 return array($formValues, $categories, $html_message, $messageToken, $returnProperties);
306 * process the form after the input has been submitted and validated
312 static function postProcess(&$form) {
313 list($formValues, $categories, $html_message, $messageToken, $returnProperties) = self
::processMessageTemplate($form);
315 $skipOnHold = isset($form->skipOnHold
) ?
$form->skipOnHold
: FALSE;
316 $skipDeceased = isset($form->skipDeceased
) ?
$form->skipDeceased
: TRUE;
318 foreach ($form->_contactIds
as $item => $contactId) {
319 $params = array('contact_id' => $contactId);
321 list($contact) = CRM_Utils_Token
::getTokenDetails($params,
327 'CRM_Contact_Form_Task_PDFLetterCommon'
329 if (civicrm_error($contact)) {
330 $notSent[] = $contactId;
334 $tokenHtml = CRM_Utils_Token
::replaceContactTokens($html_message, $contact[$contactId], TRUE, $messageToken);
335 $tokenHtml = CRM_Utils_Token
::replaceHookTokens($tokenHtml, $contact[$contactId], $categories, TRUE);
337 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
338 $smarty = CRM_Core_Smarty
::singleton();
339 // also add the contact tokens to the template
340 $smarty->assign_by_ref('contact', $contact);
341 $tokenHtml = $smarty->fetch("string:$tokenHtml");
344 $html[] = $tokenHtml;
347 self
::createActivities($form, $html_message, $form->_contactIds
);
349 CRM_Utils_PDF_Utils
::html2pdf($html, "CiviLetter.pdf", FALSE, $formValues);
351 $form->postProcessHook();
353 CRM_Utils_System
::civiExit(1);
356 function createActivities($form, $html_message, $contactIds) {
358 $session = CRM_Core_Session
::singleton();
359 $userID = $session->get('userID');
360 $activityTypeID = CRM_Core_OptionGroup
::getValue(
365 $activityParams = array(
366 'source_contact_id' => $userID,
367 'activity_type_id' => $activityTypeID,
368 'activity_date_time' => date('YmdHis'),
369 'details' => $html_message,
371 if (!empty($form->_activityId
)) {
372 $activityParams +
= array('id' => $form->_activityId
);
375 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
378 // create Print PDF activity for each selected contact. CRM-6886
379 $activityIds = array();
380 foreach ($contactIds as $contactId) {
381 $activityID = CRM_Activity_BAO_Activity
::create($activityParams);
382 $activityIds[$contactId] = $activityID->id
;
386 foreach ($form->_contactIds
as $contactId) {
387 $activityTargetParams = array(
388 'activity_id' => empty($activity->id
) ?
$activityIds[$contactId] : $activity->id
,
389 'contact_id' => $contactId,
390 'record_type' => 'Target'
392 CRM_Activity_BAO_ActivityContact
::create($activityTargetParams);
396 function formatMessage(&$message) {
397 $newLineOperators = array(
400 'pattern' => '/<(\s+)?p(\s+)?>/m',
404 'pattern' => '/<(\s+)?br(\s+)?\/>/m',
408 $htmlMsg = preg_split($newLineOperators['p']['pattern'], $message);
409 foreach ($htmlMsg as $k => & $m) {
410 $messages = preg_split($newLineOperators['br']['pattern'], $m);
411 foreach ($messages as $key => & $msg) {
414 if (preg_match('/^( )+/', $msg, $matches)) {
415 $spaceLen = strlen($matches[0]) / 6;
416 $trimMsg = ltrim($msg, ' ');
417 $charLen = strlen($trimMsg);
418 $totalLen = $charLen +
$spaceLen;
419 if ($totalLen > 100) {
421 if ($spaceLen > 50) {
424 if ($charLen > 100) {
427 $msg = str_repeat(' ', $spacesCount) . $trimMsg;
431 $m = implode($newLineOperators['br']['oper'], $messages);
433 $message = implode($newLineOperators['p']['oper'], $htmlMsg);