3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
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 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
);
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 * This function sets the 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);
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 (!CRM_Utils_Array
::value($token, $customFormatProperties)) {
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 (CRM_Utils_Array
::value('location_type_id', $fv)) {
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 (CRM_Utils_Array
::value('do_not_mail', $fv)) {
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 && CRM_Utils_Array
::value($locName, $contact)) {
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 unset($contact[$locName]);
271 if (CRM_Utils_Array
::value('county_id', $contact)) {
272 unset($contact['county_id']);
275 foreach ($contact as $field => $fieldValue) {
276 $rows[$value][$field] = $fieldValue;
279 $valuesothers = array();
280 $paramsothers = array('contact_id' => $value);
281 $valuesothers = CRM_Core_BAO_Location
::getValues($paramsothers, $valuesothers);
282 if (CRM_Utils_Array
::value('location_type_id', $fv)) {
283 foreach ($valuesothers as $vals) {
284 if ( CRM_Utils_Array
::value('location_type_id', $vals) ==
285 CRM_Utils_Array
::value('location_type_id', $fv ) ) {
286 foreach ($vals as $k => $v) {
287 if (in_array($k, array(
288 'email', 'phone', 'im', 'openid'))) {
290 $rows[$value][$k] = $v['1']['name'];
293 $rows[$value][$k] = $v['1'][$k];
295 $rows[$value][$k . '_id'] = $v['1']['id'];
303 if(!$this->tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) {
307 if (CRM_Utils_Array
::value('addressee_display', $contact)) {
308 $contact['addressee_display'] = trim($contact['addressee_display']);
310 if (CRM_Utils_Array
::value('addressee', $contact)) {
311 $contact['addressee'] = $contact['addressee_display'];
314 // now create the rows for generating mailing labels
315 foreach ($contact as $field => $fieldValue) {
316 $rows[$value][$field] = $fieldValue;
321 if (isset($fv['merge_same_address'])) {
322 $this->mergeSameAddress($rows);
323 $individualFormat = TRUE;
326 // format the addresses according to CIVICRM_ADDRESS_FORMAT (CRM-1327)
327 foreach ($rows as $id => $row) {
328 if ($commMethods = CRM_Utils_Array
::value('preferred_communication_method', $row)) {
329 $val = array_filter(explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $commMethods));
330 $comm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
332 foreach ($val as $vals) {
333 $temp[] = $comm[$vals];
335 $row['preferred_communication_method'] = implode(', ', $temp);
338 $formatted = CRM_Utils_Address
::format($row, 'mailing_format', FALSE, TRUE, $individualFormat, $tokenFields);
340 // CRM-2211: UFPDF doesn't have bidi support; use the PECL fribidi package to fix it.
341 // On Ubuntu (possibly Debian?) be aware of http://pecl.php.net/bugs/bug.php?id=12366
342 // Due to FriBidi peculiarities, this can't be called on
343 // a multi-line string, hence the explode+implode approach.
344 if (function_exists('fribidi_log2vis')) {
345 $lines = explode("\n", $formatted);
346 foreach ($lines as $i => $line) {
347 $lines[$i] = fribidi_log2vis($line, FRIBIDI_AUTO
, FRIBIDI_CHARSET_UTF8
);
349 $formatted = implode("\n", $lines);
351 $rows[$id] = array($formatted);
354 //call function to create labels
355 self
::createLabel($rows, $fv['label_name']);
356 CRM_Utils_System
::civiExit(1);
360 * Check for presence of tokens to be swapped out
361 * @param array $contact
362 * @param array $mailingFormatProperties
363 * @param array $tokenFields
365 function tokenIsFound($contact, $mailingFormatProperties, $tokenFields) {
366 foreach (array_merge($mailingFormatProperties, array_fill_keys($tokenFields, 1)) as $key => $dontCare) {
367 if (CRM_Utils_Array
::value($key, $contact)) {
374 * function to create labels (pdf)
376 * @param array $contactRows assciated array of contact data
377 * @param string $format format in which labels needs to be printed
378 * @param string $fileName The name of the file to save the label in
383 function createLabel(&$contactRows, &$format, $fileName = 'MailingLabels_CiviCRM.pdf') {
384 $pdf = new CRM_Utils_PDF_Label($format, 'mm');
388 //build contact string that needs to be printed
390 foreach ($contactRows as $row => $value) {
391 foreach ($value as $k => $v) {
395 $pdf->AddPdfLabel($val);
398 $pdf->Output($fileName, 'D');
402 * function to create the array of returnProperties
404 * @param string $format format for which return properties build
406 * @return array of returnProperties
409 function getReturnProperties(&$format) {
410 $returnProperties = array();
412 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
418 foreach ($matches[1] as $token) {
419 list($type, $name) = preg_split('/\./', $token, 2);
421 $returnProperties["{$name}"] = 1;
426 return $returnProperties;
429 function mergeSameAddress(&$rows) {
430 $uniqueAddress = array();
431 foreach (array_keys($rows) as $rowID) {
432 // load complete address as array key
434 trim($rows[$rowID]['street_address']) . trim($rows[$rowID]['city']) . trim($rows[$rowID]['state_province']) . trim($rows[$rowID]['postal_code']) . trim($rows[$rowID]['country']);
435 if (isset($rows[$rowID]['last_name'])) {
436 $name = $rows[$rowID]['last_name'];
439 $name = $rows[$rowID]['display_name'];
441 // fill uniqueAddress array with last/first name tree
442 if (isset($uniqueAddress[$address])) {
443 $uniqueAddress[$address]['names'][$name][$rows[$rowID]['first_name']]['first_name'] = $rows[$rowID]['first_name'];
444 $uniqueAddress[$address]['names'][$name][$rows[$rowID]['first_name']]['addressee_display'] = $rows[$rowID]['addressee_display'];
445 // drop unnecessary rows
446 unset($rows[$rowID]);
447 // this is the first listing at this address
450 $uniqueAddress[$address]['ID'] = $rowID;
451 $uniqueAddress[$address]['names'][$name][$rows[$rowID]['first_name']]['first_name'] = $rows[$rowID]['first_name'];
452 $uniqueAddress[$address]['names'][$name][$rows[$rowID]['first_name']]['addressee_display'] = $rows[$rowID]['addressee_display'];
455 foreach ($uniqueAddress as $address => $data) {
456 // copy data back to $rows
458 // one last name list per row
459 foreach ($data['names'] as $last_name => $first_names) {
464 if(count($first_names) == 1){
465 $family = $first_names[current(array_keys($first_names))]['addressee_display'];
468 // collapse the tree to summarize
469 $family = trim(implode(" & ", array_keys($first_names)) . " " . $last_name);
472 $processedNames .= "\n" . $family;
475 // build display_name string
476 $processedNames = $family;
480 $rows[$data['ID']]['addressee'] = $rows[$data['ID']]['addressee_display'] = $rows[$data['ID']]['display_name'] = $processedNames;