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 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->addDefaultButtons(ts('Make Mailing Labels'));
85 * This function sets the default values for the form.
89 * @return array array of default values
92 function setDefaultValues() {
94 $format = CRM_Core_BAO_LabelFormat
::getDefaultValues();
95 $defaults['label_name'] = CRM_Utils_Array
::value('name', $format);
96 $defaults['do_not_mail'] = 1;
102 * process the form after the input has been submitted and validated
108 public function postProcess() {
109 $fv = $this->controller
->exportValues($this->_name
);
110 $config = CRM_Core_Config
::singleton();
112 //get the address format sequence from the config file
113 $mailingFormat = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
117 $sequence = CRM_Utils_Address
::sequence($mailingFormat);
119 foreach ($sequence as $v) {
123 if (array_key_exists('postal_code', $address)) {
124 $address['postal_code_suffix'] = 1;
127 //build the returnproperties
128 $returnProperties = array('display_name' => 1, 'contact_type' => 1);
129 $mailingFormat = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
133 $mailingFormatProperties = array();
134 if ($mailingFormat) {
135 $mailingFormatProperties = self
::getReturnProperties($mailingFormat);
136 $returnProperties = array_merge($returnProperties, $mailingFormatProperties);
138 //we should not consider addressee for data exists, CRM-6025
139 if (array_key_exists('addressee', $mailingFormatProperties)) {
140 unset($mailingFormatProperties['addressee']);
143 $customFormatProperties = array();
144 if (stristr($mailingFormat, 'custom_')) {
145 foreach ($mailingFormatProperties as $token => $true) {
146 if (substr($token, 0, 7) == 'custom_') {
147 if (!CRM_Utils_Array
::value($token, $customFormatProperties)) {
148 $customFormatProperties[$token] = $mailingFormatProperties[$token];
154 if (!empty($customFormatProperties)) {
155 $returnProperties = array_merge($returnProperties, $customFormatProperties);
158 if (isset($fv['merge_same_address'])) {
159 // we need first name/last name for summarising to avoid spillage
160 $returnProperties['first_name'] = 1;
161 $returnProperties['last_name'] = 1;
164 //get the contacts information
166 if (CRM_Utils_Array
::value('location_type_id', $fv)) {
167 $locType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
168 $locName = $locType[$fv['location_type_id']];
169 $location = array('location' => array("{$locName}" => $address));
170 $returnProperties = array_merge($returnProperties, $location);
171 $params[] = array('location_type', '=', array($fv['location_type_id'] => 1), 0, 0);
174 $returnProperties = array_merge($returnProperties, $address);
179 foreach ($this->_contactIds
as $key => $contactID) {
181 CRM_Core_Form
::CB_PREFIX
. $contactID,
187 if (CRM_Utils_Array
::value('do_not_mail', $fv)) {
188 $params[] = array('do_not_mail', '=', 0, 0, 0);
191 $params[] = array('is_deceased', '=', 0, 0, 0);
194 foreach ($returnProperties as $name => $dontCare) {
195 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
201 //get the total number of contacts to fetch from database.
202 $numberofContacts = count($this->_contactIds
);
203 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
204 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
206 $messageToken = CRM_Utils_Token
::getTokens($mailingFormat);
208 // also get all token values
209 CRM_Utils_Hook
::tokenValues($details[0],
213 'CRM_Contact_Form_Task_Label'
217 CRM_Utils_Hook
::tokens($tokens);
218 $tokenFields = array();
219 foreach ($tokens as $category => $catTokens) {
220 foreach ($catTokens as $token => $tokenName) {
221 $tokenFields[] = $token;
225 foreach ($this->_contactIds
as $value) {
226 foreach ($custom as $cfID) {
227 if (isset($details[0][$value]["custom_{$cfID}"])) {
228 $details[0][$value]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($details[0][$value]["custom_{$cfID}"], $cfID, $details[1]);
231 $contact = CRM_Utils_Array
::value($value, $details['0']);
233 if (is_a($contact, 'CRM_Core_Error')) {
237 // we need to remove all the "_id"
238 unset($contact['contact_id']);
240 if ($locName && CRM_Utils_Array
::value($locName, $contact)) {
241 // If location type is not primary, $contact contains
242 // one more array as "$contact[$locName] = array( values... )"
245 // we should replace all the tokens that are set in mailing label format
246 foreach ($mailingFormatProperties as $key => $dontCare) {
247 if (CRM_Utils_Array
::value($key, $contact)) {
257 unset($contact[$locName]);
259 if (CRM_Utils_Array
::value('county_id', $contact)) {
260 unset($contact['county_id']);
263 foreach ($contact as $field => $fieldValue) {
264 $rows[$value][$field] = $fieldValue;
267 $valuesothers = array();
268 $paramsothers = array('contact_id' => $value);
269 $valuesothers = CRM_Core_BAO_Location
::getValues($paramsothers, $valuesothers);
270 if (CRM_Utils_Array
::value('location_type_id', $fv)) {
271 foreach ($valuesothers as $vals) {
272 if ( CRM_Utils_Array
::value('location_type_id', $vals) ==
273 CRM_Utils_Array
::value('location_type_id', $fv ) ) {
274 foreach ($vals as $k => $v) {
275 if (in_array($k, array(
276 'email', 'phone', 'im', 'openid'))) {
278 $rows[$value][$k] = $v['1']['name'];
281 $rows[$value][$k] = $v['1'][$k];
283 $rows[$value][$k . '_id'] = $v['1']['id'];
292 // we should replace all the tokens that are set in mailing label format
293 foreach ($mailingFormatProperties as $key => $dontCare) {
294 if (CRM_Utils_Array
::value($key, $contact)) {
304 if (CRM_Utils_Array
::value('addressee_display', $contact)) {
305 $contact['addressee_display'] = trim($contact['addressee_display']);
307 if (CRM_Utils_Array
::value('addressee', $contact)) {
308 $contact['addressee'] = $contact['addressee_display'];
311 // now create the rows for generating mailing labels
312 foreach ($contact as $field => $fieldValue) {
313 $rows[$value][$field] = $fieldValue;
318 $individualFormat = FALSE;
319 if (isset($fv['merge_same_address'])) {
320 $this->mergeSameAddress($rows);
321 $individualFormat = TRUE;
323 if (isset($fv['merge_same_household'])) {
324 $rows = $this->mergeSameHousehold($rows);
325 $individualFormat = TRUE;
328 // format the addresses according to CIVICRM_ADDRESS_FORMAT (CRM-1327)
329 foreach ($rows as $id => $row) {
330 if ($commMethods = CRM_Utils_Array
::value('preferred_communication_method', $row)) {
331 $val = array_filter(explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $commMethods));
332 $comm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
334 foreach ($val as $vals) {
335 $temp[] = $comm[$vals];
337 $row['preferred_communication_method'] = implode(', ', $temp);
340 $formatted = CRM_Utils_Address
::format($row, 'mailing_format', FALSE, TRUE, $individualFormat, $tokenFields);
342 // CRM-2211: UFPDF doesn't have bidi support; use the PECL fribidi package to fix it.
343 // On Ubuntu (possibly Debian?) be aware of http://pecl.php.net/bugs/bug.php?id=12366
344 // Due to FriBidi peculiarities, this can't be called on
345 // a multi-line string, hence the explode+implode approach.
346 if (function_exists('fribidi_log2vis')) {
347 $lines = explode("\n", $formatted);
348 foreach ($lines as $i => $line) {
349 $lines[$i] = fribidi_log2vis($line, FRIBIDI_AUTO
, FRIBIDI_CHARSET_UTF8
);
351 $formatted = implode("\n", $lines);
353 $rows[$id] = array($formatted);
356 //call function to create labels
357 self
::createLabel($rows, $fv['label_name']);
358 CRM_Utils_System
::civiExit(1);
362 * function to create labels (pdf)
364 * @param array $contactRows assciated array of contact data
365 * @param string $format format in which labels needs to be printed
366 * @param string $fileName The name of the file to save the label in
371 function createLabel(&$contactRows, &$format, $fileName = 'MailingLabels_CiviCRM.pdf') {
372 $pdf = new CRM_Utils_PDF_Label($format, 'mm');
376 //build contact string that needs to be printed
378 foreach ($contactRows as $row => $value) {
379 foreach ($value as $k => $v) {
383 $pdf->AddPdfLabel($val);
386 $pdf->Output($fileName, 'D');
390 * function to create the array of returnProperties
392 * @param string $format format for which return properties build
394 * @return array of returnProperties
397 function getReturnProperties(&$format) {
398 $returnProperties = array();
400 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
406 foreach ($matches[1] as $token) {
407 list($type, $name) = preg_split('/\./', $token, 2);
409 $returnProperties["{$name}"] = 1;
414 return $returnProperties;
417 function mergeSameAddress(&$rows) {
418 $uniqueAddress = array();
419 foreach (array_keys($rows) as $rowID) {
420 // load complete address as array key
422 trim($rows[$rowID]['street_address']) . trim($rows[$rowID]['city']) . trim($rows[$rowID]['state_province']) . trim($rows[$rowID]['postal_code']) . trim($rows[$rowID]['country']);
423 if (isset($rows[$rowID]['last_name'])) {
424 $name = $rows[$rowID]['last_name'];
427 $name = $rows[$rowID]['display_name'];
429 // fill uniqueAddress array with last/first name tree
430 if (isset($uniqueAddress[$address])) {
431 $uniqueAddress[$address]['names'][$name][] = $rows[$rowID]['first_name'];
432 // drop unnecessary rows
433 unset($rows[$rowID]);
434 // this is the first listing at this address
437 $uniqueAddress[$address]['ID'] = $rowID;
438 $uniqueAddress[$address]['names'][$name][] = $rows[$rowID]['first_name'];
441 foreach ($uniqueAddress as $address => $data) {
442 // copy data back to $rows
444 // one last name list per row
445 foreach ($data['names'] as $last_name => $first_names) {
450 // collapse the tree to summarize
451 $family = trim(implode(" & ", $first_names) . " " . $last_name);
453 $processedNames .= "\n" . $family;
456 // build display_name string
457 $processedNames = $family;
461 $rows[$data['ID']]['addressee'] = $rows[$data['ID']]['addressee_display'] = $rows[$data['ID']]['display_name'] = $processedNames;
465 function mergeSameHousehold(&$rows) {
466 # group selected contacts by type
467 $individuals = array();
468 $households = array();
469 foreach ($rows as $contact_id => $row) {
470 if ($row['contact_type'] == 'Household') {
471 $households[$contact_id] = $row;
473 elseif ($row['contact_type'] == 'Individual') {
474 $individuals[$contact_id] = $row;
478 # exclude individuals belonging to selected households
479 foreach ($households as $household_id => $row) {
480 $dao = new CRM_Contact_DAO_Relationship();
481 $dao->contact_id_b
= $household_id;
483 while ($dao->fetch()) {
484 $individual_id = $dao->contact_id_a
;
485 if (array_key_exists($individual_id, $individuals)) {
486 unset($individuals[$individual_id]);
491 # merge back individuals and households
492 $rows = array_merge($individuals, $households);