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 helps to print the labels for contacts
40 class CRM_Contact_Form_Task_Label
extends CRM_Contact_Form_Task
{
43 * Build all the data structures needed to build the form
48 function preProcess() {
49 $this->set('contactIds', $this->_contactIds
);
54 * Build the form object
60 function buildQuickForm() {
61 CRM_Utils_System
::setTitle(ts('Make Mailing Labels'));
63 //add select for label
64 $label = CRM_Core_BAO_LabelFormat
::getList(TRUE);
66 $this->add('select', 'label_name', ts('Select Label'), array('' => ts('- select label -')) +
$label, TRUE);
69 // add select for Location Type
70 $this->addElement('select', 'location_type_id', ts('Select Location'),
72 '' => ts('Primary')) + CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id'), TRUE
75 // checkbox for SKIP contacts with Do Not Mail privacy option
76 $this->addElement('checkbox', 'do_not_mail', ts('Do not print labels for contacts with "Do Not Mail" privacy option checked'));
78 $this->add('checkbox', 'merge_same_address', ts('Merge labels for contacts with the same address'), NULL);
79 $this->add('checkbox', 'merge_same_household', ts('Merge labels for contacts belonging to the same household'), NULL);
81 $this->addButtons(array(
84 'name' => ts('Make Mailing Labels'),
95 * Set default values for the form.
99 * @return array array of default values
102 function setDefaultValues() {
104 $format = CRM_Core_BAO_LabelFormat
::getDefaultValues();
105 $defaults['label_name'] = CRM_Utils_Array
::value('name', $format);
106 $defaults['do_not_mail'] = 1;
112 * Process the form after the input has been submitted and validated
118 public function postProcess() {
119 $fv = $this->controller
->exportValues($this->_name
);
120 $config = CRM_Core_Config
::singleton();
122 //get the address format sequence from the config file
123 $mailingFormat = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
127 $sequence = CRM_Utils_Address
::sequence($mailingFormat);
129 foreach ($sequence as $v) {
133 if (array_key_exists('postal_code', $address)) {
134 $address['postal_code_suffix'] = 1;
137 //build the returnproperties
138 $returnProperties = array('display_name' => 1, 'contact_type' => 1, 'prefix_id' => 1);
139 $mailingFormat = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
143 $mailingFormatProperties = array();
144 if ($mailingFormat) {
145 $mailingFormatProperties = self
::getReturnProperties($mailingFormat);
146 $returnProperties = array_merge($returnProperties, $mailingFormatProperties);
148 //we should not consider addressee for data exists, CRM-6025
149 if (array_key_exists('addressee', $mailingFormatProperties)) {
150 unset($mailingFormatProperties['addressee']);
153 $customFormatProperties = array();
154 if (stristr($mailingFormat, 'custom_')) {
155 foreach ($mailingFormatProperties as $token => $true) {
156 if (substr($token, 0, 7) == 'custom_') {
157 if (empty($customFormatProperties[$token])) {
158 $customFormatProperties[$token] = $mailingFormatProperties[$token];
164 if (!empty($customFormatProperties)) {
165 $returnProperties = array_merge($returnProperties, $customFormatProperties);
168 if (isset($fv['merge_same_address'])) {
169 // we need first name/last name for summarising to avoid spillage
170 $returnProperties['first_name'] = 1;
171 $returnProperties['last_name'] = 1;
174 $individualFormat = FALSE;
177 * CRM-8338: replace ids of household members with the id of their household
178 * so we can merge labels by household.
180 if (isset($fv['merge_same_household'])) {
181 $this->mergeContactIdsByHousehold();
182 $individualFormat = TRUE;
185 //get the contacts information
187 if (!empty($fv['location_type_id'])) {
188 $locType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
189 $locName = $locType[$fv['location_type_id']];
190 $location = array('location' => array("{$locName}" => $address));
191 $returnProperties = array_merge($returnProperties, $location);
192 $params[] = array('location_type', '=', array($fv['location_type_id'] => 1), 0, 0);
195 $returnProperties = array_merge($returnProperties, $address);
200 foreach ($this->_contactIds
as $key => $contactID) {
202 CRM_Core_Form
::CB_PREFIX
. $contactID,
208 if (!empty($fv['do_not_mail'])) {
209 $params[] = array('do_not_mail', '=', 0, 0, 0);
212 $params[] = array('is_deceased', '=', 0, 0, 0);
215 foreach ($returnProperties as $name => $dontCare) {
216 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
222 //get the total number of contacts to fetch from database.
223 $numberofContacts = count($this->_contactIds
);
224 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
225 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
227 $messageToken = CRM_Utils_Token
::getTokens($mailingFormat);
229 // also get all token values
230 CRM_Utils_Hook
::tokenValues($details[0],
234 'CRM_Contact_Form_Task_Label'
238 CRM_Utils_Hook
::tokens($tokens);
239 $tokenFields = array();
240 foreach ($tokens as $category => $catTokens) {
241 foreach ($catTokens as $token => $tokenName) {
242 $tokenFields[] = $token;
246 foreach ($this->_contactIds
as $value) {
247 foreach ($custom as $cfID) {
248 if (isset($details[0][$value]["custom_{$cfID}"])) {
249 $details[0][$value]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($details[0][$value]["custom_{$cfID}"], $cfID, $details[1]);
252 $contact = CRM_Utils_Array
::value($value, $details['0']);
254 if (is_a($contact, 'CRM_Core_Error')) {
258 // we need to remove all the "_id"
259 unset($contact['contact_id']);
261 if ($locName && !empty($contact[$locName])) {
262 // If location type is not primary, $contact contains
263 // one more array as "$contact[$locName] = array( values... )"
265 if(!$this->tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) {
269 $contact = array_merge($contact, $contact[$locName]);
270 unset($contact[$locName]);
272 if (!empty($contact['county_id'])) {
273 unset($contact['county_id']);
276 foreach ($contact as $field => $fieldValue) {
277 $rows[$value][$field] = $fieldValue;
280 $valuesothers = array();
281 $paramsothers = array('contact_id' => $value);
282 $valuesothers = CRM_Core_BAO_Location
::getValues($paramsothers, $valuesothers);
283 if (!empty($fv['location_type_id'])) {
284 foreach ($valuesothers as $vals) {
285 if ( CRM_Utils_Array
::value('location_type_id', $vals) ==
286 CRM_Utils_Array
::value('location_type_id', $fv ) ) {
287 foreach ($vals as $k => $v) {
288 if (in_array($k, array(
289 'email', 'phone', 'im', 'openid'))) {
291 $rows[$value][$k] = $v['1']['name'];
294 $rows[$value][$k] = $v['1'][$k];
296 $rows[$value][$k . '_id'] = $v['1']['id'];
304 if(!$this->tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) {
308 if (!empty($contact['addressee_display'])) {
309 $contact['addressee_display'] = trim($contact['addressee_display']);
311 if (!empty($contact['addressee'])) {
312 $contact['addressee'] = $contact['addressee_display'];
315 // now create the rows for generating mailing labels
316 foreach ($contact as $field => $fieldValue) {
317 $rows[$value][$field] = $fieldValue;
322 if (isset($fv['merge_same_address'])) {
323 $this->mergeSameAddress($rows);
324 $individualFormat = TRUE;
327 // format the addresses according to CIVICRM_ADDRESS_FORMAT (CRM-1327)
328 foreach ($rows as $id => $row) {
329 if ($commMethods = CRM_Utils_Array
::value('preferred_communication_method', $row)) {
330 $val = array_filter(explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $commMethods));
331 $comm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
333 foreach ($val as $vals) {
334 $temp[] = $comm[$vals];
336 $row['preferred_communication_method'] = implode(', ', $temp);
339 $formatted = CRM_Utils_Address
::format($row, 'mailing_format', FALSE, TRUE, $individualFormat, $tokenFields);
341 // CRM-2211: UFPDF doesn't have bidi support; use the PECL fribidi package to fix it.
342 // On Ubuntu (possibly Debian?) be aware of http://pecl.php.net/bugs/bug.php?id=12366
343 // Due to FriBidi peculiarities, this can't be called on
344 // a multi-line string, hence the explode+implode approach.
345 if (function_exists('fribidi_log2vis')) {
346 $lines = explode("\n", $formatted);
347 foreach ($lines as $i => $line) {
348 $lines[$i] = fribidi_log2vis($line, FRIBIDI_AUTO
, FRIBIDI_CHARSET_UTF8
);
350 $formatted = implode("\n", $lines);
352 $rows[$id] = array($formatted);
355 //call function to create labels
356 self
::createLabel($rows, $fv['label_name']);
357 CRM_Utils_System
::civiExit(1);
361 * Check for presence of tokens to be swapped out
363 * @param array $contact
364 * @param array $mailingFormatProperties
365 * @param array $tokenFields
369 function tokenIsFound($contact, $mailingFormatProperties, $tokenFields) {
370 foreach (array_merge($mailingFormatProperties, array_fill_keys($tokenFields, 1)) as $key => $dontCare) {
371 if (!empty($contact[$key])) {
378 * Create labels (pdf)
380 * @param array $contactRows assciated array of contact data
381 * @param string $format format in which labels needs to be printed
382 * @param string $fileName The name of the file to save the label in
387 function createLabel(&$contactRows, &$format, $fileName = 'MailingLabels_CiviCRM.pdf') {
388 $pdf = new CRM_Utils_PDF_Label($format, 'mm');
392 //build contact string that needs to be printed
394 foreach ($contactRows as $row => $value) {
395 foreach ($value as $k => $v) {
399 $pdf->AddPdfLabel($val);
402 $pdf->Output($fileName, 'D');
406 * Create the array of returnProperties
408 * @param string $format format for which return properties build
410 * @return array of returnProperties
413 function getReturnProperties(&$format) {
414 $returnProperties = array();
416 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
422 foreach ($matches[1] as $token) {
423 list($type, $name) = preg_split('/\./', $token, 2);
425 $returnProperties["{$name}"] = 1;
430 return $returnProperties;
436 function mergeSameAddress(&$rows) {
437 $uniqueAddress = array();
438 foreach (array_keys($rows) as $rowID) {
439 // load complete address as array key
441 trim($rows[$rowID]['street_address']) . trim($rows[$rowID]['city']) . trim($rows[$rowID]['state_province']) . trim($rows[$rowID]['postal_code']) . trim($rows[$rowID]['country']);
442 if (isset($rows[$rowID]['last_name'])) {
443 $name = $rows[$rowID]['last_name'];
446 $name = $rows[$rowID]['display_name'];
451 'first_name' => $rows[$rowID]['first_name'],
452 'individual_prefix' => $rows[$rowID]['individual_prefix']
454 $format = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
, 'display_name_format');
455 $firstNameWithPrefix = CRM_Utils_Address
::format($formatted, $format, FALSE, FALSE, TRUE);
456 $firstNameWithPrefix = trim($firstNameWithPrefix);
458 // fill uniqueAddress array with last/first name tree
459 if (isset($uniqueAddress[$address])) {
460 $uniqueAddress[$address]['names'][$name][$firstNameWithPrefix]['first_name'] = $rows[$rowID]['first_name'];
461 $uniqueAddress[$address]['names'][$name][$firstNameWithPrefix]['addressee_display'] = $rows[$rowID]['addressee_display'];
462 // drop unnecessary rows
463 unset($rows[$rowID]);
464 // this is the first listing at this address
467 $uniqueAddress[$address]['ID'] = $rowID;
468 $uniqueAddress[$address]['names'][$name][$firstNameWithPrefix]['first_name'] = $rows[$rowID]['first_name'];
469 $uniqueAddress[$address]['names'][$name][$firstNameWithPrefix]['addressee_display'] = $rows[$rowID]['addressee_display'];
472 foreach ($uniqueAddress as $address => $data) {
473 // copy data back to $rows
475 // one last name list per row
476 foreach ($data['names'] as $last_name => $first_names) {
481 if(count($first_names) == 1){
482 $family = $first_names[current(array_keys($first_names))]['addressee_display'];
485 // collapse the tree to summarize
486 $family = trim(implode(" & ", array_keys($first_names)) . " " . $last_name);
489 $processedNames .= "\n" . $family;
492 // build display_name string
493 $processedNames = $family;
497 $rows[$data['ID']]['addressee'] = $rows[$data['ID']]['addressee_display'] = $rows[$data['ID']]['display_name'] = $processedNames;