Merge remote-tracking branch 'upstream/4.5' into 4.5-master-2015-01-12-16-09-32
[civicrm-core.git] / CRM / Contact / Form / Task / Batch.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * This class provides the functionality for batch profile update
38 */
39 class CRM_Contact_Form_Task_Batch extends CRM_Contact_Form_Task {
40
41 /**
42 * The title of the group
43 *
44 * @var string
45 */
46 protected $_title;
47
48 /**
49 * Maximum contacts that should be allowed to update
50 */
51 protected $_maxContacts = 100;
52
53 /**
54 * Maximum profile fields that will be displayed
55 */
56 protected $_maxFields = 9;
57
58 /**
59 * Variable to store redirect path
60 */
61 protected $_userContext;
62
63 /**
64 * When not to reset sort_name
65 */
66 protected $_preserveDefault = TRUE;
67
68 /**
69 * Build all the data structures needed to build the form
70 *
71 * @return void
72 */
73 public function preProcess() {
74 /*
75 * initialize the task and row fields
76 */
77 parent::preProcess();
78 }
79
80 /**
81 * Build the form object
82 *
83 *
84 * @return void
85 */
86 public function buildQuickForm() {
87 $ufGroupId = $this->get('ufGroupId');
88
89 if (!$ufGroupId) {
90 CRM_Core_Error::fatal('ufGroupId is missing');
91 }
92 $this->_title = ts('Batch Update') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId);
93 CRM_Utils_System::setTitle($this->_title);
94
95 $this->addDefaultButtons(ts('Save'));
96 $this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW);
97
98 // remove file type field and then limit fields
99 $suppressFields = FALSE;
100 $removehtmlTypes = array('File', 'Autocomplete-Select');
101 foreach ($this->_fields as $name => $field) {
102 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) &&
103 in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
104 ) {
105 $suppressFields = TRUE;
106 unset($this->_fields[$name]);
107 }
108 }
109
110 //FIX ME: phone ext field is added at the end and it gets removed because of below code
111 //$this->_fields = array_slice($this->_fields, 0, $this->_maxFields);
112
113 $this->addButtons(array(
114 array(
115 'type' => 'submit',
116 'name' => ts('Update Contact(s)'),
117 'isDefault' => TRUE,
118 ),
119 array(
120 'type' => 'cancel',
121 'name' => ts('Cancel'),
122 ),
123 )
124 );
125
126
127 $this->assign('profileTitle', $this->_title);
128 $this->assign('componentIds', $this->_contactIds);
129
130 // if below fields are missing we should not reset sort name / display name
131 // CRM-6794
132 $preserveDefaultsArray = array(
133 'first_name',
134 'last_name',
135 'middle_name',
136 'organization_name',
137 'prefix_id',
138 'suffix_id',
139 'household_name',
140 );
141
142 foreach ($this->_contactIds as $contactId) {
143 $profileFields = $this->_fields;
144 CRM_Core_BAO_Address::checkContactSharedAddressFields($profileFields, $contactId);
145 foreach ($profileFields as $name => $field) {
146 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $contactId);
147
148 if (in_array($field['name'], $preserveDefaultsArray)) {
149 $this->_preserveDefault = FALSE;
150 }
151 }
152 }
153
154 $this->assign('fields', $this->_fields);
155
156 // don't set the status message when form is submitted.
157 $buttonName = $this->controller->getButtonName('submit');
158
159 if ($suppressFields && $buttonName != '_qf_BatchUpdateProfile_next') {
160 CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Batch Update."), ts('Some Fields Excluded'), 'info');
161 }
162
163 $this->addDefaultButtons(ts('Update Contacts'));
164 $this->addFormRule(array('CRM_Contact_Form_Task_Batch', 'formRule'));
165 }
166
167 /**
168 * Set default values for the form.
169 *
170 *
171 * @return array
172 */
173 public function setDefaultValues() {
174 if (empty($this->_fields)) {
175 return;
176 }
177
178 $defaults = $sortName = array();
179 foreach ($this->_contactIds as $contactId) {
180 $details[$contactId] = array();
181
182 //build sortname
183 $sortName[$contactId] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
184 $contactId,
185 'sort_name'
186 );
187
188 CRM_Core_BAO_UFGroup::setProfileDefaults($contactId, $this->_fields, $defaults, FALSE);
189 }
190
191 $this->assign('sortName', $sortName);
192
193 return $defaults;
194 }
195
196 /**
197 * Global form rule
198 *
199 * @param array $fields
200 * The input form values.
201 *
202 * @return bool|array
203 * true if no errors, else array of errors
204 * @static
205 */
206 public static function formRule($fields) {
207 $errors = array();
208 $externalIdentifiers = array();
209 foreach ($fields['field'] as $componentId => $field) {
210 foreach ($field as $fieldName => $fieldValue) {
211 if ($fieldName == 'external_identifier') {
212 if (in_array($fieldValue, $externalIdentifiers)) {
213 $errors["field[$componentId][external_identifier]"] = ts('Duplicate value for External ID.');
214 }
215 else {
216 $externalIdentifiers[$componentId] = $fieldValue;
217 }
218 }
219 }
220 }
221
222 return $errors;
223 }
224
225 /**
226 * Process the form after the input has been submitted and validated
227 *
228 *
229 * @return void
230 */
231 public function postProcess() {
232 $params = $this->exportValues();
233
234 $ufGroupId = $this->get('ufGroupId');
235 $notify = NULL;
236 $inValidSubtypeCnt = 0;
237 //send profile notification email if 'notify' field is set
238 $notify = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $ufGroupId, 'notify');
239 foreach ($params['field'] as $key => $value) {
240
241 //CRM-5521
242 //validate subtype before updating
243 if (!empty($value['contact_sub_type']) && !CRM_Contact_BAO_ContactType::isAllowEdit($key)) {
244 unset($value['contact_sub_type']);
245 $inValidSubtypeCnt++;
246 }
247
248 $value['preserveDBName'] = $this->_preserveDefault;
249
250 //parse street address, CRM-7768
251 self::parseStreetAddress($value, $this);
252
253 CRM_Contact_BAO_Contact::createProfileContact($value, $this->_fields, $key, NULL, $ufGroupId, NULL, TRUE);
254 if ($notify) {
255 $values = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($ufGroupId, $key, NULL);
256 CRM_Core_BAO_UFGroup::commonSendMail($key, $values);
257 }
258 }
259
260 CRM_Core_Session::setStatus('', ts("Updates Saved"), 'success');
261 if ($inValidSubtypeCnt) {
262 CRM_Core_Session::setStatus(ts('Contact Subtype field of 1 contact has not been updated.', array(
263 'plural' => 'Contact Subtype field of %count contacts has not been updated.',
264 'count' => $inValidSubtypeCnt
265 )), ts('Invalid Subtype'));
266 }
267 }
268
269 /**
270 * Parse street address
271 * @param array $contactValues
272 * Contact values.
273 * @param CRM_Core_Form $form
274 * Form object.
275 */
276 public static function parseStreetAddress(&$contactValues, &$form) {
277 if (!is_array($contactValues) || !is_array($form->_fields)) {
278 return;
279 }
280
281 static $parseAddress;
282 $addressFldKey = 'street_address';
283 if (!isset($parseAddress)) {
284 $parseAddress = FALSE;
285 foreach ($form->_fields as $key => $fld) {
286 if (strpos($key, $addressFldKey) !== FALSE) {
287 $parseAddress = CRM_Utils_Array::value('street_address_parsing',
288 CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
289 'address_options'
290 ),
291 FALSE
292 );
293 break;
294 }
295 }
296 }
297
298 if (!$parseAddress) {
299 return;
300 }
301
302 $allParseValues = array();
303 foreach ($contactValues as $key => $value) {
304 if (strpos($key, $addressFldKey) !== FALSE) {
305 $locTypeId = substr($key, strlen($addressFldKey) + 1);
306
307 // parse address field.
308 $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($value);
309
310 //street address consider to be parsed properly,
311 //If we get street_name and street_number.
312 if (empty($parsedFields['street_name']) || empty($parsedFields['street_number'])) {
313 $parsedFields = array_fill_keys(array_keys($parsedFields), '');
314 }
315
316 //merge parse values.
317 foreach ($parsedFields as $fldKey => $parseVal) {
318 if ($locTypeId) {
319 $fldKey .= "-{$locTypeId}";
320 }
321 $allParseValues[$fldKey] = $parseVal;
322 }
323 }
324 }
325
326 //finally merge all parse values
327 if (!empty($allParseValues)) {
328 $contactValues += $allParseValues;
329 }
330 }
331 }