Merge pull request #18286 from sunilpawar/ui_30
[civicrm-core.git] / CRM / Contact / Form / Task / Label.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class helps to print the labels for contacts.
20 */
21 class CRM_Contact_Form_Task_Label extends CRM_Contact_Form_Task {
22
23 /**
24 * Build all the data structures needed to build the form.
25 */
26 public function preProcess() {
27 $this->set('contactIds', $this->_contactIds);
28 parent::preProcess();
29 }
30
31 /**
32 * Build the form object.
33 */
34 public function buildQuickForm() {
35 self::buildLabelForm($this);
36 }
37
38 /**
39 * Common Function to build Mailing Label Form.
40 *
41 * @param CRM_Core_Form $form
42 */
43 public static function buildLabelForm($form) {
44 CRM_Utils_System::setTitle(ts('Make Mailing Labels'));
45
46 //add select for label
47 $label = CRM_Core_BAO_LabelFormat::getList(TRUE);
48
49 $form->add('select', 'label_name', ts('Select Label'), ['' => ts('- select label -')] + $label, TRUE);
50
51 // add select for Location Type
52 $form->addElement('select', 'location_type_id', ts('Select Location'),
53 [
54 '' => ts('Primary'),
55 ] + CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'), TRUE
56 );
57
58 // checkbox for SKIP contacts with Do Not Mail privacy option
59 $form->addElement('checkbox', 'do_not_mail', ts('Do not print labels for contacts with "Do Not Mail" privacy option checked'));
60
61 $form->add('checkbox', 'merge_same_address', ts('Merge labels for contacts with the same address'), NULL);
62 $form->add('checkbox', 'merge_same_household', ts('Merge labels for contacts belonging to the same household'), NULL);
63
64 $form->addButtons([
65 [
66 'type' => 'submit',
67 'name' => ts('Make Mailing Labels'),
68 'isDefault' => TRUE,
69 ],
70 [
71 'type' => 'cancel',
72 'name' => ts('Done'),
73 ],
74 ]);
75 }
76
77 /**
78 * Set default values for the form.
79 *
80 * @return array
81 * array of default values
82 */
83 public function setDefaultValues() {
84 $defaults = [];
85 $format = CRM_Core_BAO_LabelFormat::getDefaultValues();
86 $defaults['label_name'] = $format['name'] ?? NULL;
87 $defaults['do_not_mail'] = 1;
88
89 return $defaults;
90 }
91
92 /**
93 * Process the form after the input has been submitted and validated.
94 *
95 * @param array|NULL $params
96 */
97 public function postProcess($params = NULL) {
98 $fv = $params ?: $this->controller->exportValues($this->_name);
99 $config = CRM_Core_Config::singleton();
100 $locName = NULL;
101 //get the address format sequence from the config file
102 $mailingFormat = Civi::settings()->get('mailing_format');
103
104 $sequence = CRM_Utils_Address::sequence($mailingFormat);
105
106 foreach ($sequence as $v) {
107 $address[$v] = 1;
108 }
109
110 if (array_key_exists('postal_code', $address)) {
111 $address['postal_code_suffix'] = 1;
112 }
113
114 //build the returnproperties
115 $returnProperties = ['display_name' => 1, 'contact_type' => 1, 'prefix_id' => 1];
116 $mailingFormat = Civi::settings()->get('mailing_format');
117
118 $mailingFormatProperties = [];
119 if ($mailingFormat) {
120 $mailingFormatProperties = CRM_Utils_Token::getReturnProperties($mailingFormat);
121 $returnProperties = array_merge($returnProperties, $mailingFormatProperties);
122 }
123 //we should not consider addressee for data exists, CRM-6025
124 if (array_key_exists('addressee', $mailingFormatProperties)) {
125 unset($mailingFormatProperties['addressee']);
126 }
127
128 $customFormatProperties = [];
129 if (stristr($mailingFormat, 'custom_')) {
130 foreach ($mailingFormatProperties as $token => $true) {
131 if (substr($token, 0, 7) == 'custom_') {
132 if (empty($customFormatProperties[$token])) {
133 $customFormatProperties[$token] = $mailingFormatProperties[$token];
134 }
135 }
136 }
137 }
138
139 if (!empty($customFormatProperties)) {
140 $returnProperties = array_merge($returnProperties, $customFormatProperties);
141 }
142
143 if (isset($fv['merge_same_address'])) {
144 // we need first name/last name for summarising to avoid spillage
145 $returnProperties['first_name'] = 1;
146 $returnProperties['last_name'] = 1;
147 }
148
149 $individualFormat = FALSE;
150
151 /*
152 * CRM-8338: replace ids of household members with the id of their household
153 * so we can merge labels by household.
154 */
155 if (isset($fv['merge_same_household'])) {
156 $this->mergeContactIdsByHousehold();
157 $individualFormat = TRUE;
158 }
159
160 //get the contacts information
161 $params = [];
162 if (!empty($fv['location_type_id'])) {
163 $locType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
164 $locName = $locType[$fv['location_type_id']];
165 $location = ['location' => ["{$locName}" => $address]];
166 $returnProperties = array_merge($returnProperties, $location);
167 $params[] = ['location_type', '=', [1 => $fv['location_type_id']], 0, 0];
168 $primaryLocationOnly = FALSE;
169 }
170 else {
171 $returnProperties = array_merge($returnProperties, $address);
172 $primaryLocationOnly = TRUE;
173 }
174
175 $rows = [];
176 foreach ($this->_contactIds as $key => $contactID) {
177 $params[] = [
178 CRM_Core_Form::CB_PREFIX . $contactID,
179 '=',
180 1,
181 0,
182 0,
183 ];
184 }
185
186 // fix for CRM-2651
187 if (!empty($fv['do_not_mail'])) {
188 $params[] = ['do_not_mail', '=', 0, 0, 0];
189 }
190 // fix for CRM-2613
191 $params[] = ['is_deceased', '=', 0, 0, 0];
192
193 $custom = [];
194 foreach ($returnProperties as $name => $dontCare) {
195 $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
196 if ($cfID) {
197 $custom[] = $cfID;
198 }
199 }
200
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, TRUE, FALSE, TRUE, CRM_Contact_BAO_Query::MODE_CONTACTS, NULL, $primaryLocationOnly);
205 $messageToken = CRM_Utils_Token::getTokens($mailingFormat);
206
207 // $details[0] is an array of [ contactID => contactDetails ]
208 // also get all token values
209 CRM_Utils_Hook::tokenValues($details[0],
210 $this->_contactIds,
211 NULL,
212 $messageToken,
213 'CRM_Contact_Form_Task_Label'
214 );
215
216 $tokens = [];
217 CRM_Utils_Hook::tokens($tokens);
218 $tokenFields = [];
219 foreach ($tokens as $category => $catTokens) {
220 foreach ($catTokens as $token => $tokenName) {
221 $tokenFields[] = $token;
222 }
223 }
224
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::displayValue($details[0][$value]["custom_{$cfID}"], $cfID);
229 }
230 }
231 $contact = $details['0'][$value] ?? NULL;
232
233 if (is_a($contact, 'CRM_Core_Error')) {
234 return NULL;
235 }
236
237 // we need to remove all the "_id"
238 unset($contact['contact_id']);
239
240 if ($locName && !empty($contact[$locName])) {
241 // If location type is not primary, $contact contains
242 // one more array as "$contact[$locName] = array( values... )"
243
244 if (!self::tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) {
245 continue;
246 }
247
248 $contact = array_merge($contact, $contact[$locName]);
249 unset($contact[$locName]);
250
251 if (!empty($contact['county_id'])) {
252 unset($contact['county_id']);
253 }
254
255 foreach ($contact as $field => $fieldValue) {
256 $rows[$value][$field] = $fieldValue;
257 }
258
259 $valuesothers = [];
260 $paramsothers = ['contact_id' => $value];
261 $valuesothers = CRM_Core_BAO_Location::getValues($paramsothers, $valuesothers);
262 if (!empty($fv['location_type_id'])) {
263 foreach ($valuesothers as $vals) {
264 if (CRM_Utils_Array::value('location_type_id', $vals) ==
265 CRM_Utils_Array::value('location_type_id', $fv)
266 ) {
267 foreach ($vals as $k => $v) {
268 if (in_array($k, [
269 'email',
270 'phone',
271 'im',
272 'openid',
273 ])) {
274 if ($k == 'im') {
275 $rows[$value][$k] = $v['1']['name'];
276 }
277 else {
278 $rows[$value][$k] = $v['1'][$k];
279 }
280 $rows[$value][$k . '_id'] = $v['1']['id'];
281 }
282 }
283 }
284 }
285 }
286 }
287 else {
288 if (!self::tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) {
289 continue;
290 }
291
292 if (!empty($contact['addressee_display'])) {
293 $contact['addressee_display'] = trim($contact['addressee_display']);
294 }
295 if (!empty($contact['addressee'])) {
296 $contact['addressee'] = $contact['addressee_display'];
297 }
298
299 // now create the rows for generating mailing labels
300 foreach ($contact as $field => $fieldValue) {
301 $rows[$value][$field] = $fieldValue;
302 }
303 }
304 }
305
306 if (isset($fv['merge_same_address'])) {
307 CRM_Core_BAO_Address::mergeSameAddress($rows);
308 $individualFormat = TRUE;
309 }
310
311 // format the addresses according to CIVICRM_ADDRESS_FORMAT (CRM-1327)
312 foreach ($rows as $id => $row) {
313 if ($commMethods = CRM_Utils_Array::value('preferred_communication_method', $row)) {
314 $val = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $commMethods));
315 $comm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
316 $temp = [];
317 foreach ($val as $vals) {
318 $temp[] = $comm[$vals];
319 }
320 $row['preferred_communication_method'] = implode(', ', $temp);
321 }
322 $row['id'] = $id;
323 $formatted = CRM_Utils_Address::format($row, 'mailing_format', FALSE, TRUE, $tokenFields);
324
325 // CRM-2211: UFPDF doesn't have bidi support; use the PECL fribidi package to fix it.
326 // On Ubuntu (possibly Debian?) be aware of http://pecl.php.net/bugs/bug.php?id=12366
327 // Due to FriBidi peculiarities, this can't be called on
328 // a multi-line string, hence the explode+implode approach.
329 if (function_exists('fribidi_log2vis')) {
330 $lines = explode("\n", $formatted);
331 foreach ($lines as $i => $line) {
332 $lines[$i] = fribidi_log2vis($line, FRIBIDI_AUTO, FRIBIDI_CHARSET_UTF8);
333 }
334 $formatted = implode("\n", $lines);
335 }
336 $rows[$id] = [$formatted];
337 }
338
339 if (!empty($fv['is_unit_testing'])) {
340 return $rows;
341 }
342
343 //call function to create labels
344 self::createLabel($rows, $fv['label_name']);
345 CRM_Utils_System::civiExit();
346 }
347
348 /**
349 * Check for presence of tokens to be swapped out.
350 *
351 * @param array $contact
352 * @param array $mailingFormatProperties
353 * @param array $tokenFields
354 *
355 * @return bool
356 */
357 public static function tokenIsFound($contact, $mailingFormatProperties, $tokenFields) {
358 foreach (array_merge($mailingFormatProperties, array_fill_keys($tokenFields, 1)) as $key => $dontCare) {
359 //we should not consider addressee for data exists, CRM-6025
360 if ($key != 'addressee' && !empty($contact[$key])) {
361 return TRUE;
362 }
363 }
364 return FALSE;
365 }
366
367 /**
368 * Create labels (pdf).
369 *
370 * @param array $contactRows
371 * Associated array of contact data.
372 * @param string $format
373 * Format in which labels needs to be printed.
374 * @param string $fileName
375 * The name of the file to save the label in.
376 */
377 public function createLabel(&$contactRows, &$format, $fileName = 'MailingLabels_CiviCRM.pdf') {
378 $pdf = new CRM_Utils_PDF_Label($format, 'mm');
379 $pdf->Open();
380 $pdf->AddPage();
381
382 //build contact string that needs to be printed
383 $val = NULL;
384 foreach ($contactRows as $row => $value) {
385 foreach ($value as $k => $v) {
386 $val .= "$v\n";
387 }
388
389 $pdf->AddPdfLabel($val);
390 $val = '';
391 }
392 $pdf->Output($fileName, 'D');
393 }
394
395 }