Merge pull request #6643 from davecivicrm/CRM-17031
[civicrm-core.git] / CRM / Contact / Form / Task / LabelCommon.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 */
33
34 /**
35 * This class provides the common functionality for sending email to one or a group of contact ids.
36 */
37 class CRM_Contact_Form_Task_LabelCommon {
38
39 /**
40 * Create labels (pdf).
41 *
42 * @param array $contactRows
43 * Associated array of contact data.
44 * @param string $format
45 * Format in which labels needs to be printed.
46 * @param string $fileName
47 * The name of the file to save the label in.
48 */
49 public static function createLabel(&$contactRows, &$format, $fileName = 'MailingLabels_CiviCRM.pdf') {
50 $pdf = new CRM_Utils_PDF_Label($format, 'mm');
51 $pdf->Open();
52 $pdf->AddPage();
53
54 //build contact string that needs to be printed
55 $val = NULL;
56 foreach ($contactRows as $row => $value) {
57 foreach ($value as $k => $v) {
58 $val .= "$v\n";
59 }
60
61 $pdf->AddPdfLabel($val);
62 $val = '';
63 }
64 $pdf->Output($fileName, 'D');
65 }
66
67
68 /**
69 * Get the rows for the labels.
70 *
71 * @param $contactIDs
72 * @param int $locationTypeID
73 * @param bool $respectDoNotMail
74 * @param $mergeSameAddress
75 * @param bool $mergeSameHousehold
76 * UNUSED.
77 *
78 * @return array
79 * Array of rows for labels
80 */
81 public static function getRows($contactIDs, $locationTypeID, $respectDoNotMail, $mergeSameAddress, $mergeSameHousehold) {
82 $locName = NULL;
83 //get the address format sequence from the config file
84 $addressReturnProperties = CRM_Contact_Form_Task_LabelCommon::getAddressReturnProperties();
85
86 //build the return properties
87 $returnProperties = array('display_name' => 1, 'contact_type' => 1, 'prefix_id' => 1);
88 $mailingFormat = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
89 'mailing_format'
90 );
91
92 $mailingFormatProperties = array();
93 if ($mailingFormat) {
94 $mailingFormatProperties = CRM_Utils_Token::getReturnProperties($mailingFormat);
95 $returnProperties = array_merge($returnProperties, $mailingFormatProperties);
96 }
97
98 $customFormatProperties = array();
99 if (stristr($mailingFormat, 'custom_')) {
100 foreach ($mailingFormatProperties as $token => $true) {
101 if (substr($token, 0, 7) == 'custom_') {
102 if (empty($customFormatProperties[$token])) {
103 $customFormatProperties[$token] = $mailingFormatProperties[$token];
104 }
105 }
106 }
107 }
108 $returnProperties = array_merge($returnProperties, $customFormatProperties);
109
110 if ($mergeSameAddress) {
111 // we need first name/last name for summarising to avoid spillage
112 $returnProperties['first_name'] = 1;
113 $returnProperties['last_name'] = 1;
114 }
115
116 //get the contacts information
117 $params = $custom = array();
118 foreach ($contactIDs as $key => $contactID) {
119 $params[] = array(
120 CRM_Core_Form::CB_PREFIX . $contactID,
121 '=',
122 1,
123 0,
124 0,
125 );
126 }
127
128 // fix for CRM-2651
129 if (!empty($respectDoNotMail['do_not_mail'])) {
130 $params[] = array('do_not_mail', '=', 0, 0, 0);
131 }
132 // fix for CRM-2613
133 $params[] = array('is_deceased', '=', 0, 0, 0);
134
135 if ($locationTypeID) {
136 $locType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
137 $locName = $locType[$locationTypeID];
138 $location = array('location' => array("{$locName}" => $addressReturnProperties));
139 $returnProperties = array_merge($returnProperties, $location);
140 $params[] = array('location_type', '=', array($locationTypeID => 1), 0, 0);
141 }
142 else {
143 $returnProperties = array_merge($returnProperties, $addressReturnProperties);
144 }
145
146 foreach ($returnProperties as $name) {
147 $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
148 if ($cfID) {
149 $custom[] = $cfID;
150 }
151 }
152
153 //get the total number of contacts to fetch from database.
154 $numberofContacts = count($contactIDs);
155 //this does the same as calling civicrm_api3('contact, get, array('id' => array('IN' => $this->_contactIds)
156 // except it also handles multiple locations
157 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
158 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
159
160 $messageToken = CRM_Utils_Token::getTokens($mailingFormat);
161 $details = $details[0];
162 $tokenFields = CRM_Contact_Form_Task_LabelCommon::getTokenData($details);
163
164 foreach ($contactIDs as $value) {
165 foreach ($custom as $cfID) {
166 if (isset($details[$value]["custom_{$cfID}"])) {
167 $details[$value]["custom_{$cfID}"] = CRM_Core_BAO_CustomField::getDisplayValue($details[$value]["custom_{$cfID}"], $cfID, $details[1]);
168 }
169 }
170 $contact = CRM_Utils_Array::value($value, $details);
171
172 if (is_a($contact, 'CRM_Core_Error')) {
173 return NULL;
174 }
175
176 // we need to remove all the "_id"
177 unset($contact['contact_id']);
178
179 if ($locName && !empty($contact[$locName])) {
180 // If location type is not primary, $contact contains
181 // one more array as "$contact[$locName] = array( values... )"
182
183 if (!CRM_Contact_Form_Task_Label::tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) {
184 continue;
185 }
186
187 unset($contact[$locName]);
188
189 if (!empty($contact['county_id'])) {
190 unset($contact['county_id']);
191 }
192
193 foreach ($contact as $field => $fieldValue) {
194 $rows[$value][$field] = $fieldValue;
195 }
196
197 $valuesothers = array();
198 $paramsothers = array('contact_id' => $value);
199 $valuesothers = CRM_Core_BAO_Location::getValues($paramsothers, $valuesothers);
200 if ($locationTypeID) {
201 foreach ($valuesothers as $vals) {
202 if (CRM_Utils_Array::value('location_type_id', $vals) ==
203 $locationTypeID
204 ) {
205 foreach ($vals as $k => $v) {
206 if (in_array($k, array(
207 'email',
208 'phone',
209 'im',
210 'openid',
211 ))) {
212 if ($k == 'im') {
213 $rows[$value][$k] = $v['1']['name'];
214 }
215 else {
216 $rows[$value][$k] = $v['1'][$k];
217 }
218 $rows[$value][$k . '_id'] = $v['1']['id'];
219 }
220 }
221 }
222 }
223 }
224 }
225 else {
226 if (!CRM_Contact_Form_Task_Label::tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) {
227 continue;
228 }
229
230 if (!empty($contact['addressee_display'])) {
231 $contact['addressee_display'] = trim($contact['addressee_display']);
232 }
233 if (!empty($contact['addressee'])) {
234 $contact['addressee'] = $contact['addressee_display'];
235 }
236
237 // now create the rows for generating mailing labels
238 foreach ($contact as $field => $fieldValue) {
239 $rows[$value][$field] = $fieldValue;
240 }
241 }
242 }
243 // sigh couldn't extract out tokenfields yet
244 return array($rows, $tokenFields);
245 }
246
247 /**
248 * Get array of return properties for address fields required for mailing label.
249 *
250 * @return array
251 * return properties for address e.g
252 * [street_address => 1, supplemental_address_1 => 1, supplemental_address_2 => 1]
253 */
254 public static function getAddressReturnProperties() {
255 $mailingFormat = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
256 'mailing_format'
257 );
258
259 $addressFields = CRM_Utils_Address::sequence($mailingFormat);
260 $addressReturnProperties = array_fill_keys($addressFields, 1);
261
262 if (array_key_exists('postal_code', $addressReturnProperties)) {
263 $addressReturnProperties['postal_code_suffix'] = 1;
264 }
265 return $addressReturnProperties;
266 }
267
268 /**
269 * Get token list from mailing format & contacts
270 * @param array $contacts
271 * @return array
272 */
273 public static function getTokenData(&$contacts) {
274 $mailingFormat = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
275 'mailing_format'
276 );
277 $tokens = $tokenFields = array();
278 $messageToken = CRM_Utils_Token::getTokens($mailingFormat);
279
280 // also get all token values
281 CRM_Utils_Hook::tokenValues($contacts,
282 array_keys($contacts),
283 NULL,
284 $messageToken,
285 'CRM_Contact_Form_Task_LabelCommon'
286 );
287
288 CRM_Utils_Hook::tokens($tokens);
289
290 foreach ($tokens as $category => $catTokens) {
291 foreach ($catTokens as $token => $tokenName) {
292 $tokenFields[] = $token;
293 }
294 }
295 return $tokenFields;
296
297 }
298
299 /**
300 * @param array $rows
301 *
302 * @return array
303 */
304 public function mergeSameHousehold(&$rows) {
305 // group selected contacts by type
306 $individuals = array();
307 $households = array();
308 foreach ($rows as $contact_id => $row) {
309 if ($row['contact_type'] == 'Household') {
310 $households[$contact_id] = $row;
311 }
312 elseif ($row['contact_type'] == 'Individual') {
313 $individuals[$contact_id] = $row;
314 }
315 }
316
317 // exclude individuals belonging to selected households
318 foreach ($households as $household_id => $row) {
319 $dao = new CRM_Contact_DAO_Relationship();
320 $dao->contact_id_b = $household_id;
321 $dao->find();
322 while ($dao->fetch()) {
323 $individual_id = $dao->contact_id_a;
324 if (array_key_exists($individual_id, $individuals)) {
325 unset($individuals[$individual_id]);
326 }
327 }
328 }
329
330 // merge back individuals and households
331 $rows = array_merge($individuals, $households);
332 return $rows;
333 }
334
335 }