[REF] don't handle non-array, pass by reference
[civicrm-core.git] / CRM / Contact / Form / Merge.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
32 */
33
34 /**
35 * Class CRM_Contact_Form_Merge.
36 */
37 class CRM_Contact_Form_Merge extends CRM_Core_Form {
38 // The id of the contact that there's a duplicate for; this one will
39 /**
40 * possibly inherit some of $_oid's properties and remain in the system.
41 * @var int
42 */
43 public $_cid = NULL;
44
45 /**
46 * The id of the other contact - the duplicate one that will get deleted.
47 * @var int
48 */
49 public $_oid = NULL;
50
51 public $_contactType = NULL;
52
53 /**
54 * @var array
55 */
56 public $criteria = [];
57
58 /**
59 * Query limit to be retained in the urls.
60 *
61 * @var int
62 */
63 public $limit;
64
65 /**
66 * String for quickform bug handling.
67 *
68 * FIXME: QuickForm can't create advcheckboxes with value set to 0 or '0' :(
69 * see HTML_QuickForm_advcheckbox::setValues() - but patching that doesn't
70 * help, as QF doesn't put the 0-value elements in exportValues() anyway...
71 * to side-step this, we use the below UUID as a (re)placeholder
72 *
73 * @var string
74 */
75 public $_qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
76
77 public function preProcess() {
78 try {
79
80 $this->_cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
81 $this->_oid = CRM_Utils_Request::retrieve('oid', 'Positive', $this, TRUE);
82 $flip = CRM_Utils_Request::retrieve('flip', 'Positive', $this, FALSE);
83
84 $this->_rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, FALSE);
85 $this->_gid = $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE);
86 $this->_mergeId = CRM_Utils_Request::retrieve('mergeId', 'Positive', $this, FALSE);
87 $this->limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this, FALSE);
88 $this->criteria = CRM_Utils_Request::retrieve('criteria', 'Json', $this, FALSE, '{}');
89
90 $urlParams = ['reset' => 1, 'rgid' => $this->_rgid, 'gid' => $this->_gid, 'limit' => $this->limit, 'criteria' => $this->criteria];
91
92 $this->bounceIfInvalid($this->_cid, $this->_oid);
93
94 $contacts = civicrm_api3('Contact', 'get', [
95 'id' => ['IN' => [$this->_cid, $this->_oid]],
96 'return' => ['contact_type', 'modified_date', 'created_date', 'contact_sub_type'],
97 ])['values'];
98
99 $this->_contactType = $contacts[$this->_cid]['contact_type'];
100
101 $browseUrl = CRM_Utils_System::url('civicrm/contact/dedupefind', array_merge($urlParams, ['action' => 'browse']));
102
103 if (!$this->_rgid) {
104 // Unset browse URL as we have come from the search screen.
105 $browseUrl = '';
106 $this->_rgid = civicrm_api3('RuleGroup', 'getvalue', [
107 'contact_type' => $this->_contactType,
108 'used' => 'Supervised',
109 'return' => 'id',
110 ]);
111 }
112 $this->assign('browseUrl', $browseUrl);
113 if ($browseUrl) {
114 CRM_Core_Session::singleton()->pushUserContext($browseUrl);
115 }
116
117 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $gid, json_decode($this->criteria, TRUE), TRUE, $this->limit);
118
119 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
120 $where = "de.id IS NULL";
121
122 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, $this->_cid, $this->_oid, $this->_mergeId, $join, $where, $flip);
123
124 // get user info of main contact.
125 $config = CRM_Core_Config::singleton();
126 CRM_Core_Config::setPermitCacheFlushMode(FALSE);
127
128 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($this->_cid);
129 $mainUser = NULL;
130 if ($mainUfId) {
131 $mainUser = $config->userSystem->getUser($this->_cid);
132 $this->assign('mainUfId', $mainUfId);
133 $this->assign('mainUfName', $mainUser ? $mainUser['name'] : NULL);
134 }
135 $flipParams = array_merge($urlParams, ['action' => 'update', 'cid' => $this->_oid, 'oid' => $this->_cid]);
136 if (!$flip) {
137 $flipParams['flip'] = '1';
138 }
139 $flipUrl = CRM_Utils_System::url('civicrm/contact/merge',
140 $flipParams
141 );
142 $this->assign('flip', $flipUrl);
143
144 $this->prev = $this->next = NULL;
145 foreach ([
146 'prev',
147 'next',
148 ] as $position) {
149 if (!empty($pos[$position])) {
150 if ($pos[$position]['id1'] && $pos[$position]['id2']) {
151 $rowParams = array_merge($urlParams, [
152 'action' => 'update',
153 'cid' => $pos[$position]['id1'],
154 'oid' => $pos[$position]['id2'],
155 'mergeId' => $pos[$position]['mergeId'],
156 ]);
157 $this->$position = CRM_Utils_System::url('civicrm/contact/merge', $rowParams);
158 $this->assign($position, $this->$position);
159 }
160 }
161 }
162
163 // get user info of other contact.
164 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($this->_oid);
165 $otherUser = NULL;
166
167 if ($otherUfId) {
168 $otherUser = $config->userSystem->getUser($this->_oid);
169 $this->assign('otherUfId', $otherUfId);
170 $this->assign('otherUfName', $otherUser ? $otherUser['name'] : NULL);
171 }
172
173 $cmsUser = ($mainUfId && $otherUfId) ? TRUE : FALSE;
174 $this->assign('user', $cmsUser);
175
176 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($this->_cid, $this->_oid);
177 $main = $this->_mainDetails = $rowsElementsAndInfo['main_details'];
178 $other = $this->_otherDetails = $rowsElementsAndInfo['other_details'];
179
180 $this->assign('contact_type', $main['contact_type']);
181 $this->assign('main_name', $main['display_name']);
182 $this->assign('other_name', $other['display_name']);
183 $this->assign('main_cid', $main['contact_id']);
184 $this->assign('other_cid', $other['contact_id']);
185 $this->assign('rgid', $this->_rgid);
186 $this->assignSummaryRowsToTemplate($contacts);
187
188 $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
189
190 $this->assign('mainLocBlock', json_encode($rowsElementsAndInfo['main_details']['location_blocks']));
191 $this->assign('locationBlockInfo', json_encode(CRM_Dedupe_Merger::getLocationBlockInfo()));
192 $this->assign('mainContactTypeIcon', CRM_Contact_BAO_Contact_Utils::getImage($contacts[$this->_cid]['contact_sub_type'] ? $contacts[$this->_cid]['contact_sub_type'] : $contacts[$this->_cid]['contact_type'],
193 FALSE,
194 $this->_cid
195 ));
196 $this->assign('otherContactTypeIcon', CRM_Contact_BAO_Contact_Utils::getImage($contacts[$this->_oid]['contact_sub_type'] ? $contacts[$this->_oid]['contact_sub_type'] : $contacts[$this->_oid]['contact_type'],
197 FALSE,
198 $this->_oid
199 ));
200
201 if (isset($rowsElementsAndInfo['rows']['move_contact_type'])) {
202 // We don't permit merging contacts of different types so this is just clutter - putting
203 // the icon next to the contact name is consistent with elsewhere and permits hover-info
204 // https://lab.civicrm.org/dev/core/issues/824
205 unset($rowsElementsAndInfo['rows']['move_contact_type']);
206 }
207
208 $this->assign('rows', $rowsElementsAndInfo['rows']);
209
210 // add elements
211 foreach ($rowsElementsAndInfo['elements'] as $element) {
212 // We could push this down to the getRowsElementsAndInfo function but it's
213 // already so overloaded - let's start moving towards doing form-things
214 // on the form.
215 if (substr($element[1], 0, 13) === 'move_location') {
216 $element[4] = array_merge(
217 (array) CRM_Utils_Array::value(4, $element, []),
218 [
219 'data-location' => substr($element[1], 14),
220 'data-is_location' => TRUE,
221 ]);
222 }
223 if (substr($element[1], 0, 15) === 'location_blocks') {
224 // @todo We could add some data elements here to make jquery manipulation more straight-forward
225 // @todo consider enabling if it is an add & defaulting to true.
226 $element[4] = array_merge((array) CRM_Utils_Array::value(4, $element, []), ['disabled' => TRUE]);
227 }
228 $this->addElement($element[0],
229 $element[1],
230 array_key_exists('2', $element) ? $element[2] : NULL,
231 array_key_exists('3', $element) ? $element[3] : NULL,
232 array_key_exists('4', $element) ? $element[4] : NULL,
233 array_key_exists('5', $element) ? $element[5] : NULL
234 );
235 }
236
237 // add related table elements
238 foreach ($rowsElementsAndInfo['rel_table_elements'] as $relTableElement) {
239 $element = $this->addElement($relTableElement[0], $relTableElement[1]);
240 $element->setChecked(TRUE);
241 }
242
243 $this->assign('rel_tables', $rowsElementsAndInfo['rel_tables']);
244 $this->assign('userContextURL', CRM_Core_Session::singleton()
245 ->readUserContext());
246 }
247 catch (CRM_Core_Exception $e) {
248 CRM_Core_Error::statusBounce($e->getMessage());
249 }
250 }
251
252 public function addRules() {
253 }
254
255 public function buildQuickForm() {
256 $this->unsavedChangesWarn = FALSE;
257 CRM_Utils_System::setTitle(ts('Merge %1 contacts', [1 => $this->_contactType]));
258 $buttons = [];
259
260 $buttons[] = [
261 'type' => 'next',
262 'name' => $this->next ? ts('Merge and go to Next Pair') : ts('Merge'),
263 'isDefault' => TRUE,
264 'icon' => $this->next ? 'fa-play-circle' : 'check',
265 ];
266
267 if ($this->next || $this->prev) {
268 $buttons[] = [
269 'type' => 'submit',
270 'name' => ts('Merge and go to Listing'),
271 ];
272 $buttons[] = [
273 'type' => 'done',
274 'name' => ts('Merge and View Result'),
275 'icon' => 'fa-check-circle',
276 ];
277 }
278
279 $buttons[] = [
280 'type' => 'cancel',
281 'name' => ts('Cancel'),
282 ];
283
284 $this->addButtons($buttons);
285 $this->addFormRule(['CRM_Contact_Form_Merge', 'formRule'], $this);
286 }
287
288 /**
289 * @param $fields
290 * @param $files
291 * @param $self
292 *
293 * @return array
294 */
295 public static function formRule($fields, $files, $self) {
296 $errors = [];
297 $link = CRM_Utils_System::href(ts('Flip between the original and duplicate contacts.'),
298 'civicrm/contact/merge',
299 'reset=1&action=update&cid=' . $self->_oid . '&oid=' . $self->_cid . '&rgid=' . $self->_rgid . '&flip=1'
300 );
301 if (CRM_Contact_BAO_Contact::checkDomainContact($self->_oid)) {
302 $errors['_qf_default'] = ts("The Default Organization contact cannot be merged into another contact record. It is associated with the CiviCRM installation for this domain and contains information used for system functions. If you want to merge these records, you can: %1", [1 => $link]);
303 }
304 return $errors;
305 }
306
307 public function postProcess() {
308 $formValues = $this->exportValues();
309
310 $formValues['main_details'] = $this->_mainDetails;
311 $formValues['other_details'] = $this->_otherDetails;
312 $migrationData = ['migration_info' => $formValues];
313 CRM_Utils_Hook::merge('form', $migrationData, $this->_cid, $this->_oid);
314 CRM_Dedupe_Merger::moveAllBelongings($this->_cid, $this->_oid, $migrationData['migration_info']);
315
316 $name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_cid, 'display_name');
317 $message = '<ul><li>' . ts('%1 has been updated.', [1 => $name]) . '</li><li>' . ts('Contact ID %1 has been deleted.', [1 => $this->_oid]) . '</li></ul>';
318 CRM_Core_Session::setStatus($message, ts('Contacts Merged'), 'success');
319
320 $urlParams = ['reset' => 1, 'cid' => $this->_cid, 'rgid' => $this->_rgid, 'gid' => $this->_gid, 'limit' => $this->limit, 'criteria' => $this->criteria];
321 $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', ['reset' => 1, 'cid' => $this->_cid]);
322
323 if (!empty($formValues['_qf_Merge_submit'])) {
324 $urlParams['action'] = "update";
325 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/dedupefind',
326 $urlParams
327 ));
328 }
329 if (!empty($formValues['_qf_Merge_done'])) {
330 CRM_Utils_System::redirect($contactViewUrl);
331 }
332
333 if ($this->next && $this->_mergeId) {
334 $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $this->_gid, json_decode($this->criteria, TRUE), TRUE, $this->limit);
335
336 $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
337 $where = "de.id IS NULL";
338
339 $pos = CRM_Core_BAO_PrevNextCache::getPositions($cacheKey, NULL, NULL, $this->_mergeId, $join, $where);
340
341 if (!empty($pos) &&
342 $pos['next']['id1'] &&
343 $pos['next']['id2']
344 ) {
345
346 $urlParams['cid'] = $pos['next']['id1'];
347 $urlParams['oid'] = $pos['next']['id2'];
348 $urlParams['mergeId'] = $pos['next']['mergeId'];
349 $urlParams['action'] = 'update';
350 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/merge', $urlParams));
351 }
352 }
353
354 // Perhaps never reached.
355 CRM_Utils_System::redirect($contactViewUrl);
356 }
357
358 /**
359 * Bounce if the merge action is invalid.
360 *
361 * We don't allow the merge if it is nonsensical, marked as a duplicate
362 * or outside the user's permission.
363 *
364 * @param int $cid
365 * Contact ID to retain
366 * @param int $oid
367 * Contact ID to delete.
368 */
369 public function bounceIfInvalid($cid, $oid) {
370 if ($cid == $oid) {
371 CRM_Core_Error::statusBounce(ts('Cannot merge a contact with itself.'));
372 }
373
374 if (!CRM_Dedupe_BAO_Rule::validateContacts($cid, $oid)) {
375 CRM_Core_Error::statusBounce(ts('The selected pair of contacts are marked as non duplicates. If these records should be merged, you can remove this exception on the <a href="%1">Dedupe Exceptions</a> page.', [1 => CRM_Utils_System::url('civicrm/dedupe/exception', 'reset=1')]));
376 }
377
378 if (!(CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT) &&
379 CRM_Contact_BAO_Contact_Permission::allow($oid, CRM_Core_Permission::EDIT)
380 )
381 ) {
382 CRM_Utils_System::permissionDenied();
383 }
384 // ensure that oid is not the current user, if so refuse to do the merge
385 if (CRM_Core_Session::singleton()->getLoggedInContactID() == $oid) {
386 $message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.',
387 [1 => CRM_Core_Session::singleton()->getLoggedInContactDisplayName()]
388 );
389 CRM_Core_Error::statusBounce($message);
390 }
391 }
392
393 /**
394 * Assign the summary_rows variable to the tpl.
395 *
396 * This adds rows to the beginning of the block that will help in making merge choices.
397 *
398 * It can be modified by a hook by altering what is assigned. Although not technically supported this
399 * is an easy tweak with no earth-shattering impacts if later changes stop if from working.
400 *
401 * https://lab.civicrm.org/dev/core/issues/824
402 *
403 * @param array $contacts
404 */
405 protected function assignSummaryRowsToTemplate($contacts) {
406 $mostRecent = ($contacts[$this->_cid]['modified_date'] < $contacts[$this->_oid]['modified_date']) ? $this->_oid : $this->_cid;
407 $this->assign('summary_rows', [
408 [
409 'name' => 'created_date',
410 'label' => ts('Created'),
411 'main_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_cid]['created_date']),
412 'other_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_oid]['created_date']),
413 ],
414 [
415 'name' => 'modified_date',
416 'label' => ts('Last Modified'),
417 'main_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_cid]['modified_date']) . ($mostRecent == $this->_cid ? ' (' . ts('Most Recent') . ')' : ''),
418 'other_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_oid]['modified_date']) . ($mostRecent == $this->_oid ? ' (' . ts('Most Recent') . ')' : ''),
419 ],
420 ]);
421 }
422
423 }