CRM-13966 - Refactor autocomplete custom field
[civicrm-core.git] / CRM / Contact / Page / AJAX.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 *
33 */
34
35 /**
36 * This class contains all contact related functions that are called using AJAX (jQuery)
37 */
38 class CRM_Contact_Page_AJAX {
39 static function getContactList() {
40 // if context is 'customfield'
41 if (CRM_Utils_Array::value('context', $_GET) == 'customfield') {
42 return self::contactReference();
43 }
44
45 $params = array('version' => 3, 'check_permissions' => TRUE);
46
47 // String params
48 // FIXME: param keys don't match input keys, using this array to translate
49 $whitelist = array(
50 's' => 'name',
51 'fieldName' => 'field_name',
52 'tableName' => 'table_name',
53 'context' => 'context',
54 'rel' => 'rel',
55 'contact_sub_type' => 'contact_sub_type',
56 'contact_type' => 'contact_type'
57 );
58 foreach ($whitelist as $key => $param) {
59 if (!empty($_GET[$key])) {
60 $params[$param] = $_GET[$key];
61 }
62 }
63
64 //CRM-10687: Allow quicksearch by multiple fields
65 if (!empty($params['field_name'])) {
66 if ($params['field_name'] == 'phone_numeric') {
67 $params['name'] = preg_replace('/[^\d]/', '', $params['name']);
68 }
69 if (!$params['name']) {
70 CRM_Utils_System::civiExit();
71 }
72 }
73
74 // Numeric params
75 $whitelist = array(
76 'limit',
77 'org',
78 'employee_id',
79 'cid',
80 'id',
81 'cmsuser',
82 );
83 foreach ($whitelist as $key) {
84 if (!empty($_GET[$key]) && is_numeric($_GET[$key])) {
85 $params[$key] = $_GET[$key];
86 }
87 }
88
89 $result = civicrm_api('Contact', 'getquick', $params);
90 CRM_Core_Page_AJAX::autocompleteResults(CRM_Utils_Array::value('values', $result), 'data');
91 }
92
93 static function contactReference() {
94 $name = CRM_Utils_Array::value('s', $_GET);
95 $name = CRM_Utils_Type::escape($name, 'String');
96 $cfID = CRM_Utils_Type::escape($_GET['id'], 'Positive');
97
98 // check that this is a valid, active custom field of Contact Reference type
99 $params = array('id' => $cfID);
100 $returnProperties = array('filter', 'data_type', 'is_active');
101 $fldValues = array();
102 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $cf, $returnProperties);
103 if (!$cf['id'] || !$cf['is_active'] || $cf['data_type'] != 'ContactReference') {
104 CRM_Core_Page_AJAX::autocompleteResults(array('error' => $name));
105 }
106
107 if ($cf['filter']) {
108 $filterParams = array();
109 parse_str($cf['filter'], $filterParams);
110
111 $action = CRM_Utils_Array::value('action', $filterParams);
112
113 if (!empty($action) &&
114 !in_array($action, array('get', 'lookup'))
115 ) {
116 CRM_Core_Page_AJAX::autocompleteResults(array('error' => $name));
117 }
118 }
119
120 $list = array_keys(CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
121 'contact_reference_options'
122 ), '1');
123
124 $return = array_unique(array_merge(array('sort_name'), $list));
125
126 $config = CRM_Core_Config::singleton();
127
128 $limit = 10;
129 if (!empty($_GET['limit'])) {
130 $limit = CRM_Utils_Type::escape($_GET['limit'], 'Positive');
131 }
132
133 $params = array('offset' => 0, 'rowCount' => $limit, 'version' => 3);
134 foreach ($return as $fld) {
135 $params["return.{$fld}"] = 1;
136 }
137
138 if (!empty($action)) {
139 $excludeGet = array('reset', 'key', 'className', 'fnName', 'json', 'reset', 'context', 'timestamp', 'limit', 'id', 's', 'q', 'action');
140 foreach ($_GET as $param => $val) {
141 if (empty($val) ||
142 in_array($param, $excludeGet) ||
143 strpos($param, 'return.') !== FALSE ||
144 strpos($param, 'api.') !== FALSE
145 ) {
146 continue;
147 }
148 $params[$param] = $val;
149 }
150 }
151
152 if ($name) {
153 $params['sort_name'] = $name;
154 }
155
156 $params['sort'] = 'sort_name';
157
158 // tell api to skip permission chk. dgg
159 $params['check_permissions'] = 0;
160
161 // add filter variable to params
162 if (!empty($filterParams)) {
163 $params = array_merge($params, $filterParams);
164 }
165
166 $contact = civicrm_api('Contact', 'Get', $params);
167
168 if (!empty($contact['is_error'])) {
169 CRM_Core_Page_AJAX::autocompleteResults(array('error' => $name));
170 }
171
172 $contactList = array();
173 foreach ($contact['values'] as $value) {
174 $view = array();
175 foreach ($return as $fld) {
176 if (!empty($value[$fld])) {
177 $view[] = $value[$fld];
178 }
179 }
180 $contactList[$value['id']] = implode(' :: ', $view);
181 }
182
183 if (!$contactList) {
184 $contactList = array($name => $name);
185 }
186
187 CRM_Core_Page_AJAX::autocompleteResults($contactList);
188 }
189
190 /**
191 * Function to fetch PCP ID by PCP Supporter sort_name, also displays PCP title and associated Contribution Page title
192 */
193 static function getPCPList() {
194 $name = CRM_Utils_Array::value('s', $_GET);
195 $name = CRM_Utils_Type::escape($name, 'String');
196 $limit = '10';
197
198 $where = ' AND pcp.page_id = cp.id AND pcp.contact_id = cc.id';
199
200 $config = CRM_Core_Config::singleton();
201 if ($config->includeWildCardInName) {
202 $strSearch = "%$name%";
203 }
204 else {
205 $strSearch = "$name%";
206 }
207 $includeEmailFrom = $includeNickName = '';
208 if ($config->includeNickNameInName) {
209 $includeNickName = " OR nick_name LIKE '$strSearch'";
210 }
211 if ($config->includeEmailInName) {
212 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
213 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
214 }
215 else {
216 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
217 }
218
219 if (!empty($_GET['limit'])) {
220 $limit = CRM_Utils_Type::escape($_GET['limit'], 'Positive');
221 }
222
223 $select = 'cc.sort_name, pcp.title, cp.title';
224 $query = "
225 SELECT id, data
226 FROM (
227 SELECT pcp.id as id, CONCAT_WS( ' :: ', {$select} ) as data, sort_name
228 FROM civicrm_pcp pcp, civicrm_contribution_page cp, civicrm_contact cc
229 {$includeEmailFrom}
230 {$whereClause}
231 LIMIT 0, {$limit}
232 ) t
233 ORDER BY sort_name
234 ";
235
236 $dao = CRM_Core_DAO::executeQuery($query);
237 $results = array();
238 while ($dao->fetch()) {
239 $results[$dao->id] = $dao->data;
240 }
241 CRM_Core_Page_AJAX::autocompleteResults($results);
242 }
243
244 static function relationship() {
245 $relType = CRM_Utils_Array::value('rel_type', $_REQUEST);
246 $relContactID = CRM_Utils_Array::value('rel_contact', $_REQUEST);
247 $sourceContactID = CRM_Utils_Array::value('contact_id', $_REQUEST); // we no longer need this.
248 $relationshipID = CRM_Utils_Array::value('rel_id', $_REQUEST); // this used only to determine add or update mode
249 $caseID = CRM_Utils_Array::value('case_id', $_REQUEST);
250
251 // check if there are multiple clients for this case, if so then we need create
252 // relationship and also activities for each contacts
253
254 // get case client list
255 $clientList = CRM_Case_BAO_Case::getCaseClients($caseID);
256
257 foreach($clientList as $sourceContactID) {
258 $relationParams = array(
259 'relationship_type_id' => $relType . '_a_b',
260 'contact_check' => array($relContactID => 1),
261 'is_active' => 1,
262 'case_id' => $caseID,
263 'start_date' => date("Ymd"),
264 );
265
266 $relationIds = array('contact' => $sourceContactID);
267
268 // check if we are editing/updating existing relationship
269 if ($relationshipID && $relationshipID != 'null') {
270 // here we need to retrieve appropriate relationshipID based on client id and relationship type id
271 $caseRelationships = new CRM_Contact_DAO_Relationship();
272 $caseRelationships->case_id = $caseID;
273 $caseRelationships->relationship_type_id = $relType;
274 $caseRelationships->contact_id_a = $sourceContactID;
275 $caseRelationships->find();
276
277 while($caseRelationships->fetch()) {
278 $relationIds['relationship'] = $caseRelationships->id;
279 $relationIds['contactTarget'] = $relContactID;
280 }
281 $caseRelationships->free();
282 }
283
284 // create new or update existing relationship
285 $return = CRM_Contact_BAO_Relationship::create($relationParams, $relationIds);
286
287 $status = 'process-relationship-fail';
288 if (!empty($return[4][0])) {
289 $relationshipID = $return[4][0];
290 $status = 'process-relationship-success';
291
292 //create an activity for case role assignment.CRM-4480
293 CRM_Case_BAO_Case::createCaseRoleActivity($caseID, $relationshipID, $relContactID);
294 }
295 }
296
297 $relation['status'] = $status;
298 echo json_encode($relation);
299 CRM_Utils_System::civiExit();
300 }
301
302 /**
303 * Function to fetch the custom field help
304 */
305 static function customField() {
306 $fieldId = CRM_Utils_Type::escape($_REQUEST['id'], 'Integer');
307 $params = array('id' => $fieldId);
308 $returnProperties = array('help_pre', 'help_post');
309 $values = array();
310
311 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $values, $returnProperties);
312 echo json_encode($values);
313 CRM_Utils_System::civiExit();
314 }
315
316 /**
317 * Function to obtain list of permissioned employer for the given contact-id.
318 */
319 static function getPermissionedEmployer() {
320 $cid = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
321 $name = trim(CRM_Utils_Type::escape($_GET['s'], 'String'));
322 $name = str_replace('*', '%', $name);
323
324 $elements = CRM_Contact_BAO_Relationship::getPermissionedEmployer($cid, $name);
325 $results = array();
326 if (!empty($elements)) {
327 foreach ($elements as $cid => $name) {
328 $results[$cid] = $name['name'];
329 }
330 }
331 CRM_Core_Page_AJAX::autocompleteResults($results);
332 }
333
334
335 static function groupTree() {
336 $gids = CRM_Utils_Type::escape($_GET['gids'], 'String');
337 echo CRM_Contact_BAO_GroupNestingCache::json($gids);
338 CRM_Utils_System::civiExit();
339 }
340
341 /**
342 * @deprecated
343 * Old quicksearch function. No longer used in core.
344 * @todo: Remove this function and associated menu entry in CiviCRM 5
345 */
346 static function search() {
347 $json = TRUE;
348 $name = CRM_Utils_Array::value('name', $_GET, '');
349 if (!array_key_exists('name', $_GET)) {
350 $name = CRM_Utils_Array::value('s', $_GET) . '%';
351 $json = FALSE;
352 }
353 $name = CRM_Utils_Type::escape($name, 'String');
354 $whereIdClause = '';
355 if (!empty($_GET['id'])) {
356 $json = TRUE;
357 if (is_numeric($_GET['id'])) {
358 $id = CRM_Utils_Type::escape($_GET['id'], 'Integer');
359 $whereIdClause = " AND civicrm_contact.id = {$id}";
360 }
361 else {
362 $name = $_GET['id'];
363 }
364 }
365
366 $elements = array();
367 if ($name || isset($id)) {
368 $name = $name . '%';
369
370 //contact's based of relationhip type
371 $relType = NULL;
372 if (isset($_GET['rel'])) {
373 $relation = explode('_', $_GET['rel']);
374 $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
375 $rel = CRM_Utils_Type::escape($relation[2], 'String');
376 }
377
378 //shared household info
379 $shared = NULL;
380 if (isset($_GET['sh'])) {
381 $shared = CRM_Utils_Type::escape($_GET['sh'], 'Integer');
382 if ($shared == 1) {
383 $contactType = 'Household';
384 $cName = 'household_name';
385 }
386 else {
387 $contactType = 'Organization';
388 $cName = 'organization_name';
389 }
390 }
391
392 // contacts of type household
393 $hh = $addStreet = $addCity = NULL;
394 if (isset($_GET['hh'])) {
395 $hh = CRM_Utils_Type::escape($_GET['hh'], 'Integer');
396 }
397
398 //organization info
399 $organization = $street = $city = NULL;
400 if (isset($_GET['org'])) {
401 $organization = CRM_Utils_Type::escape($_GET['org'], 'Integer');
402 }
403
404 if (isset($_GET['org']) || isset($_GET['hh'])) {
405 $json = FALSE;
406 $splitName = explode(' :: ', $name);
407 if ($splitName) {
408 $contactName = trim(CRM_Utils_Array::value('0', $splitName));
409 $street = trim(CRM_Utils_Array::value('1', $splitName));
410 $city = trim(CRM_Utils_Array::value('2', $splitName));
411 }
412 else {
413 $contactName = $name;
414 }
415
416 if ($street) {
417 $addStreet = "AND civicrm_address.street_address LIKE '$street%'";
418 }
419 if ($city) {
420 $addCity = "AND civicrm_address.city LIKE '$city%'";
421 }
422 }
423
424 if ($organization) {
425
426 $query = "
427 SELECT CONCAT_WS(' :: ',sort_name,LEFT(street_address,25),city) 'sort_name',
428 civicrm_contact.id 'id'
429 FROM civicrm_contact
430 LEFT JOIN civicrm_address ON ( civicrm_contact.id = civicrm_address.contact_id
431 AND civicrm_address.is_primary=1
432 )
433 WHERE civicrm_contact.contact_type='Organization' AND organization_name LIKE '%$contactName%'
434 {$addStreet} {$addCity} {$whereIdClause}
435 ORDER BY organization_name ";
436 }
437 elseif ($shared) {
438 $query = "
439 SELECT CONCAT_WS(':::' , sort_name, supplemental_address_1, sp.abbreviation, postal_code, cc.name )'sort_name' , civicrm_contact.id 'id' , civicrm_contact.display_name 'disp' FROM civicrm_contact LEFT JOIN civicrm_address ON (civicrm_contact.id =civicrm_address.contact_id AND civicrm_address.is_primary =1 )LEFT JOIN civicrm_state_province sp ON (civicrm_address.state_province_id =sp.id )LEFT JOIN civicrm_country cc ON (civicrm_address.country_id =cc.id )WHERE civicrm_contact.contact_type ='{$contactType}' AND {$cName} LIKE '%$name%' {$whereIdClause} ORDER BY {$cName} ";
440 }
441 elseif ($hh) {
442 $query = "
443 SELECT CONCAT_WS(' :: ' , sort_name, LEFT(street_address,25),city) 'sort_name' , location_type_id 'location_type_id', is_primary 'is_primary', is_billing 'is_billing', civicrm_contact.id 'id'
444 FROM civicrm_contact
445 LEFT JOIN civicrm_address ON (civicrm_contact.id =civicrm_address.contact_id AND civicrm_address.is_primary =1 )
446 WHERE civicrm_contact.contact_type ='Household'
447 AND household_name LIKE '%$contactName%' {$addStreet} {$addCity} {$whereIdClause} ORDER BY household_name ";
448 }
449 elseif ($relType) {
450 if (!empty($_GET['case'])) {
451 $query = "
452 SELECT distinct(c.id), c.sort_name
453 FROM civicrm_contact c
454 LEFT JOIN civicrm_relationship ON civicrm_relationship.contact_id_{$rel} = c.id
455 WHERE c.sort_name LIKE '%$name%'
456 AND civicrm_relationship.relationship_type_id = $relType
457 GROUP BY sort_name
458 ";
459 }
460 }
461 else {
462
463 $query = "
464 SELECT sort_name, id
465 FROM civicrm_contact
466 WHERE sort_name LIKE '%$name'
467 {$whereIdClause}
468 ORDER BY sort_name ";
469 }
470
471 $limit = 10;
472 if (isset($_GET['limit'])) {
473 $limit = CRM_Utils_Type::escape($_GET['limit'], 'Positive');
474 }
475
476 $query .= " LIMIT 0,{$limit}";
477
478 $dao = CRM_Core_DAO::executeQuery($query);
479
480 if ($shared) {
481 while ($dao->fetch()) {
482 echo $dao->sort_name;
483 CRM_Utils_System::civiExit();
484 }
485 }
486 else {
487 while ($dao->fetch()) {
488 if ($json) {
489 $elements[] = array('name' => addslashes($dao->sort_name),
490 'id' => $dao->id,
491 );
492 }
493 else {
494 echo $elements = "$dao->sort_name|$dao->id|$dao->location_type_id|$dao->is_primary|$dao->is_billing\n";
495 }
496 }
497 //for adding new household address / organization
498 if (empty($elements) && !$json && ($hh || $organization)) {
499 echo CRM_Utils_Array::value('s', $_GET);
500 }
501 }
502 }
503
504 if (isset($_GET['sh'])) {
505 echo "";
506 CRM_Utils_System::civiExit();
507 }
508
509 if (empty($elements)) {
510 $name = str_replace('%', '', $name);
511 $elements[] = array(
512 'name' => $name,
513 'id' => $name,
514 );
515 }
516
517 if ($json) {
518 echo json_encode($elements);
519 }
520 CRM_Utils_System::civiExit();
521 }
522
523 /**
524 * Function to delete custom value
525 *
526 */
527 static function deleteCustomValue() {
528 $customValueID = CRM_Utils_Type::escape($_REQUEST['valueID'], 'Positive');
529 $customGroupID = CRM_Utils_Type::escape($_REQUEST['groupID'], 'Positive');
530
531 CRM_Core_BAO_CustomValue::deleteCustomValue($customValueID, $customGroupID);
532 $contactId = CRM_Utils_Array::value('contactId', $_REQUEST);
533 if ($contactId) {
534 echo CRM_Contact_BAO_Contact::getCountComponent('custom_' . $_REQUEST['groupID'], $contactId);
535 }
536
537 // reset the group contact cache for this group
538 CRM_Contact_BAO_GroupContactCache::remove();
539 CRM_Utils_System::civiExit();
540 }
541
542 /**
543 * Function to perform enable / disable actions on record.
544 *
545 */
546 static function enableDisable() {
547 $op = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
548 $recordID = CRM_Utils_Type::escape($_REQUEST['recordID'], 'Positive');
549 $recordBAO = CRM_Utils_Type::escape($_REQUEST['recordBAO'], 'String');
550
551 $isActive = NULL;
552 if ($op == 'disable-enable') {
553 $isActive = TRUE;
554 }
555 elseif ($op == 'enable-disable') {
556 $isActive = FALSE;
557 }
558 $status = array('status' => 'record-updated-fail');
559 if (isset($isActive)) {
560 // first munge and clean the recordBAO and get rid of any non alpha numeric characters
561 $recordBAO = CRM_Utils_String::munge($recordBAO);
562 $recordClass = explode('_', $recordBAO);
563
564 // make sure recordClass is namespaced (we cant check CRM since extensions can also use this)
565 // but it should be at least 3 levels deep
566 if (count($recordClass) >= 3) {
567 require_once (str_replace('_', DIRECTORY_SEPARATOR, $recordBAO) . ".php");
568 $method = 'setIsActive';
569
570 if (method_exists($recordBAO, $method)) {
571 $updated = call_user_func_array(array($recordBAO, $method),
572 array($recordID, $isActive)
573 );
574 if ($updated) {
575 $status = array('status' => 'record-updated-success');
576 }
577
578 // call hook enableDisable
579 CRM_Utils_Hook::enableDisable($recordBAO, $recordID, $isActive);
580 }
581 }
582 echo json_encode($status);
583 CRM_Utils_System::civiExit();
584 }
585 }
586
587 /**
588 *Function to check the CMS username
589 *
590 */
591 static public function checkUserName() {
592 $config = CRM_Core_Config::singleton();
593 $username = trim($_REQUEST['cms_name']);
594
595 $params = array('name' => $username);
596
597 $errors = array();
598 $config->userSystem->checkUserNameEmailExists($params, $errors);
599
600 if (isset($errors['cms_name']) || isset($errors['name'])) {
601 //user name is not availble
602 $user = array('name' => 'no');
603 echo json_encode($user);
604 }
605 else {
606 //user name is available
607 $user = array('name' => 'yes');
608 echo json_encode($user);
609 }
610 CRM_Utils_System::civiExit();
611 }
612
613 /**
614 * Function to get email address of a contact
615 */
616 static function getContactEmail() {
617 if (!empty($_REQUEST['contact_id'])) {
618 $contactID = CRM_Utils_Type::escape($_REQUEST['contact_id'], 'Positive');
619 list($displayName,
620 $userEmail
621 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
622 if ($userEmail) {
623 echo $userEmail;
624 }
625 }
626 else {
627 $noemail = CRM_Utils_Array::value('noemail', $_GET);
628 $queryString = NULL;
629 $name = CRM_Utils_Array::value('name', $_GET);
630 if ($name) {
631 $name = CRM_Utils_Type::escape($name, 'String');
632 if ($noemail) {
633 $queryString = " cc.sort_name LIKE '%$name%'";
634 }
635 else {
636 $queryString = " ( cc.sort_name LIKE '%$name%' OR ce.email LIKE '%$name%' ) ";
637 }
638 }
639 else {
640 $cid = CRM_Utils_Array::value('cid', $_GET);
641 if ($cid) {
642 //check cid for interger
643 $contIDS = explode(',', $cid);
644 foreach ($contIDS as $contID) {
645 CRM_Utils_Type::escape($contID, 'Integer');
646 }
647 $queryString = " cc.id IN ( $cid )";
648 }
649 }
650
651 if ($queryString) {
652 $offset = CRM_Utils_Array::value('offset', $_GET, 0);
653 $rowCount = CRM_Utils_Array::value('rowcount', $_GET, 20);
654
655 $offset = CRM_Utils_Type::escape($offset, 'Int');
656 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
657
658 // add acl clause here
659 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
660 if ($aclWhere) {
661 $aclWhere = " AND $aclWhere";
662 }
663 if ($noemail) {
664 $query = "
665 SELECT sort_name name, cc.id
666 FROM civicrm_contact cc
667 {$aclFrom}
668 WHERE cc.is_deceased = 0 AND {$queryString}
669 {$aclWhere}
670 LIMIT {$offset}, {$rowCount}
671 ";
672
673 // send query to hook to be modified if needed
674 CRM_Utils_Hook::contactListQuery($query,
675 $name,
676 CRM_Utils_Array::value('context', $_GET),
677 CRM_Utils_Array::value('cid', $_GET)
678 );
679
680 $dao = CRM_Core_DAO::executeQuery($query);
681 while ($dao->fetch()) {
682 $result[] = array(
683 'name' => $dao->name,
684 'id' => $dao->id,
685 );
686 }
687 }
688 else {
689 $query = "
690 SELECT sort_name name, ce.email, cc.id
691 FROM civicrm_email ce INNER JOIN civicrm_contact cc ON cc.id = ce.contact_id
692 {$aclFrom}
693 WHERE ce.on_hold = 0 AND cc.is_deceased = 0 AND cc.do_not_email = 0 AND {$queryString}
694 {$aclWhere}
695 LIMIT {$offset}, {$rowCount}
696 ";
697
698 // send query to hook to be modified if needed
699 CRM_Utils_Hook::contactListQuery($query,
700 $name,
701 CRM_Utils_Array::value('context', $_GET),
702 CRM_Utils_Array::value('cid', $_GET)
703 );
704
705
706 $dao = CRM_Core_DAO::executeQuery($query);
707
708 while ($dao->fetch()) {
709 $result[] = array(
710 'name' => '"' . $dao->name . '" &lt;' . $dao->email . '&gt;',
711 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->email}" : '"' . $dao->name . '" <' . $dao->email . '>',
712 );
713 }
714 }
715
716 if ($result) {
717 echo json_encode($result);
718 }
719 }
720 }
721 CRM_Utils_System::civiExit();
722 }
723
724 static function getContactPhone() {
725
726 $queryString = NULL;
727 //check for mobile type
728 $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
729 $mobileType = CRM_Utils_Array::value('Mobile', $phoneTypes);
730
731 $name = CRM_Utils_Array::value('name', $_GET);
732 if ($name) {
733 $name = CRM_Utils_Type::escape($name, 'String');
734 $queryString = " ( cc.sort_name LIKE '%$name%' OR cp.phone LIKE '%$name%' ) ";
735 }
736 else {
737 $cid = CRM_Utils_Array::value('cid', $_GET);
738 if ($cid) {
739 //check cid for interger
740 $contIDS = explode(',', $cid);
741 foreach ($contIDS as $contID) {
742 CRM_Utils_Type::escape($contID, 'Integer');
743 }
744 $queryString = " cc.id IN ( $cid )";
745 }
746 }
747
748 if ($queryString) {
749 $offset = CRM_Utils_Array::value('offset', $_GET, 0);
750 $rowCount = CRM_Utils_Array::value('rowcount', $_GET, 20);
751
752 $offset = CRM_Utils_Type::escape($offset, 'Int');
753 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
754
755 // add acl clause here
756 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
757 if ($aclWhere) {
758 $aclWhere = " AND $aclWhere";
759 }
760
761 $query = "
762 SELECT sort_name name, cp.phone, cc.id
763 FROM civicrm_phone cp INNER JOIN civicrm_contact cc ON cc.id = cp.contact_id
764 {$aclFrom}
765 WHERE cc.is_deceased = 0 AND cc.do_not_sms = 0 AND cp.phone_type_id = {$mobileType} AND {$queryString}
766 {$aclWhere}
767 LIMIT {$offset}, {$rowCount}
768 ";
769
770 // send query to hook to be modified if needed
771 CRM_Utils_Hook::contactListQuery($query,
772 $name,
773 CRM_Utils_Array::value('context', $_GET),
774 CRM_Utils_Array::value('cid', $_GET)
775 );
776
777 $dao = CRM_Core_DAO::executeQuery($query);
778
779 while ($dao->fetch()) {
780 $result[] = array(
781 'name' => '"' . $dao->name . '" &lt;' . $dao->phone . '&gt;',
782 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->phone}" : '"' . $dao->name . '" <' . $dao->phone . '>',
783 );
784 }
785 }
786
787 if ($result) {
788 echo json_encode($result);
789 }
790 CRM_Utils_System::civiExit();
791 }
792
793
794 static function buildSubTypes() {
795 $parent = CRM_Utils_Array::value('parentId', $_REQUEST);
796
797 switch ($parent) {
798 case 1:
799 $contactType = 'Individual';
800 break;
801
802 case 2:
803 $contactType = 'Household';
804 break;
805
806 case 4:
807 $contactType = 'Organization';
808 break;
809 }
810
811 $subTypes = CRM_Contact_BAO_ContactType::subTypePairs($contactType, FALSE, NULL);
812 asort($subTypes);
813 echo json_encode($subTypes);
814 CRM_Utils_System::civiExit();
815 }
816
817 static function buildDedupeRules() {
818 $parent = CRM_Utils_Array::value('parentId', $_REQUEST);
819
820 switch ($parent) {
821 case 1:
822 $contactType = 'Individual';
823 break;
824
825 case 2:
826 $contactType = 'Household';
827 break;
828
829 case 4:
830 $contactType = 'Organization';
831 break;
832 }
833
834 $dedupeRules = CRM_Dedupe_BAO_RuleGroup::getByType($contactType);
835
836 echo json_encode($dedupeRules);
837 CRM_Utils_System::civiExit();
838 }
839
840 /**
841 * Function used for CiviCRM dashboard operations
842 */
843 static function dashboard() {
844 $operation = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
845
846 switch ($operation) {
847 case 'get_widgets_by_column':
848 // This would normally be coming from either the database (this user's settings) or a default/initial dashboard configuration.
849 // get contact id of logged in user
850
851 $dashlets = CRM_Core_BAO_Dashboard::getContactDashlets();
852 break;
853
854 case 'get_widget':
855 $dashletID = CRM_Utils_Type::escape($_GET['id'], 'Positive');
856
857 $dashlets = CRM_Core_BAO_Dashboard::getDashletInfo($dashletID);
858 break;
859
860 case 'save_columns':
861 CRM_Core_BAO_Dashboard::saveDashletChanges($_REQUEST['columns']);
862 CRM_Utils_System::civiExit();
863 case 'delete_dashlet':
864 $dashletID = CRM_Utils_Type::escape($_REQUEST['dashlet_id'], 'Positive');
865 CRM_Core_BAO_Dashboard::deleteDashlet($dashletID);
866 CRM_Utils_System::civiExit();
867 }
868
869 echo json_encode($dashlets);
870 CRM_Utils_System::civiExit();
871 }
872
873 /**
874 * Function to retrieve signature based on email id
875 */
876 static function getSignature() {
877 $emailID = CRM_Utils_Type::escape($_REQUEST['emailID'], 'Positive');
878 $query = "SELECT signature_text, signature_html FROM civicrm_email WHERE id = {$emailID}";
879 $dao = CRM_Core_DAO::executeQuery($query);
880
881 $signatures = array();
882 while ($dao->fetch()) {
883 $signatures = array(
884 'signature_text' => $dao->signature_text,
885 'signature_html' => $dao->signature_html,
886 );
887 }
888
889 echo json_encode($signatures);
890 CRM_Utils_System::civiExit();
891 }
892
893 static function relationshipContacts() {
894 $searchValues = $searchRows = array();
895 $addCount = 0;
896
897 $relType = CRM_Utils_Type::escape($_REQUEST['relType'], 'String');
898 $typeName = isset($_REQUEST['typeName']) ? CRM_Utils_Type::escape($_REQUEST['typeName'], 'String') : '';
899 $relContact = CRM_Utils_Type::escape($_REQUEST['relContact'], 'String');
900 $currentContactId = CRM_Utils_Type::escape($_REQUEST['cid'], 'Integer');
901
902 if (in_array($typeName, array(
903 'Employee of', 'Employer of'))) {
904 $addCount = 1;
905 }
906
907 $sortMapper = array(
908 1 => 'sort_name', (2 + $addCount) => 'city', (3 + $addCount) => 'state_province',
909 (4 + $addCount) => 'email', (5 + $addCount) => 'phone',
910 );
911
912 $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
913 $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
914 $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
915 $sort = isset($_REQUEST['iSortCol_0']) ? $sortMapper[CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer')] : 'sort_name';
916 $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
917
918 $searchValues[] = array('sort_name', 'LIKE', $relContact, 0, 1);
919
920 list($rid, $direction) = explode('_', $relType, 2);
921
922 $relationshipType = new CRM_Contact_DAO_RelationshipType();
923
924 $relationshipType->id = $rid;
925 if ($relationshipType->find(TRUE)) {
926 if ($direction == 'a_b') {
927 $type = $relationshipType->contact_type_b;
928 $subType = $relationshipType->contact_sub_type_b;
929 }
930 else {
931 $type = $relationshipType->contact_type_a;
932 $subType = $relationshipType->contact_sub_type_a;
933 }
934
935 if ($type == 'Individual' || $type == 'Organization' || $type == 'Household') {
936 $searchValues[] = array('contact_type', '=', $type, 0, 0);
937 }
938
939 if ($subType) {
940 $searchValues[] = array('contact_sub_type', '=', $subType, 0, 0);
941 }
942 }
943
944 // exclude current contact
945 $searchValues[] = array('contact_id', '!=', $currentContactId, 0, 0);
946
947 $query = new CRM_Contact_BAO_Query($searchValues);
948 $searchCount = $query->searchQuery(0, 0, NULL, TRUE);
949 $iTotal = $searchCount;
950
951 if ($searchCount > 0) {
952 // get the result of the search
953 $result = $query->searchQuery($offset, $rowCount, $sort, FALSE, FALSE,
954 FALSE, FALSE, FALSE, NULL, $sortOrder
955 );
956
957 $config = CRM_Core_Config::singleton();
958
959 while ($result->fetch()) {
960 $query->convertToPseudoNames($result);
961 $contactID = $result->contact_id;
962 $typeImage = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ?
963 $result->contact_sub_type : $result->contact_type,
964 FALSE, $contactID
965 );
966
967 $searchRows[$contactID]['id'] = $contactID;
968 $searchRows[$contactID]['name'] = $typeImage . ' ' . $result->sort_name;
969 $searchRows[$contactID]['city'] = $result->city;
970 $searchRows[$contactID]['state'] = $result->state_province;
971 $searchRows[$contactID]['email'] = $result->email;
972 $searchRows[$contactID]['phone'] = $result->phone;
973 }
974 }
975
976 foreach ($searchRows as $cid => $row) {
977 $searchRows[$cid]['check'] = '<input type="checkbox" id="contact_check[' . $cid . ']" name="contact_check[' . $cid . ']" value=' . $cid . ' />';
978
979 if ($typeName == 'Employee of') {
980 $searchRows[$cid]['employee_of'] = '<input type="radio" name="employee_of" value=' . $cid . ' >';
981 }
982 elseif ($typeName == 'Employer of') {
983 $searchRows[$cid]['employer_of'] = '<input type="checkbox" name="employer_of[' . $cid . ']" value=' . $cid . ' />';
984 }
985 }
986
987 $selectorElements = array('check', 'name');
988 if ($typeName == 'Employee of') {
989 $selectorElements[] = 'employee_of';
990 }
991 elseif ($typeName == 'Employer of') {
992 $selectorElements[] = 'employer_of';
993 }
994 $selectorElements = array_merge($selectorElements, array('city', 'state', 'email', 'phone'));
995
996 $iFilteredTotal = $iTotal;
997 echo CRM_Utils_JSON::encodeDataTableSelector($searchRows, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
998 CRM_Utils_System::civiExit();
999 }
1000
1001 /**
1002 * Function to process dupes.
1003 *
1004 */
1005 static function processDupes() {
1006 $oper = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
1007 $cid = CRM_Utils_Type::escape($_REQUEST['cid'], 'Positive');
1008 $oid = CRM_Utils_Type::escape($_REQUEST['oid'], 'Positive');
1009
1010 if (!$oper || !$cid || !$oid) {
1011 return;
1012 }
1013
1014 $exception = new CRM_Dedupe_DAO_Exception();
1015 $exception->contact_id1 = $cid;
1016 $exception->contact_id2 = $oid;
1017 //make sure contact2 > contact1.
1018 if ($cid > $oid) {
1019 $exception->contact_id1 = $oid;
1020 $exception->contact_id2 = $cid;
1021 }
1022 $exception->find(TRUE);
1023 $status = NULL;
1024 if ($oper == 'dupe-nondupe') {
1025 $status = $exception->save();
1026 }
1027 if ($oper == 'nondupe-dupe') {
1028 $status = $exception->delete();
1029 }
1030
1031 echo json_encode(array('status' => ($status) ? $oper : $status));
1032 CRM_Utils_System::civiExit();
1033 }
1034
1035 static function getDedupes() {
1036
1037 $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
1038 $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
1039 $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
1040
1041 $gid = isset($_REQUEST['gid']) ? CRM_Utils_Type::escape($_REQUEST['gid'], 'Integer') : 0;
1042 $rgid = isset($_REQUEST['rgid']) ? CRM_Utils_Type::escape($_REQUEST['rgid'], 'Integer') : 0;
1043 $contactType = '';
1044 if ($rgid) {
1045 $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
1046 }
1047
1048 $cacheKeyString = "merge {$contactType}_{$rgid}_{$gid}";
1049 $searchRows = array();
1050 $selectorElements = array('src', 'dst', 'weight', 'actions');
1051
1052
1053 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
1054 pn.entity_id2 = de.contact_id2 )";
1055 $where = "de.id IS NULL";
1056
1057 $iFilteredTotal = $iTotal = CRM_Core_BAO_PrevNextCache::getCount($cacheKeyString, $join, $where);
1058 $mainContacts = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, $offset, $rowCount);
1059
1060 foreach ($mainContacts as $mainId => $main) {
1061 $searchRows[$mainId]['src'] = CRM_Utils_System::href($main['srcName'], 'civicrm/contact/view', "reset=1&cid={$main['srcID']}");
1062 $searchRows[$mainId]['dst'] = CRM_Utils_System::href($main['dstName'], 'civicrm/contact/view', "reset=1&cid={$main['dstID']}");
1063 $searchRows[$mainId]['weight'] = CRM_Utils_Array::value('weight', $main);
1064
1065 if (!empty($main['canMerge'])) {
1066 $mergeParams = "reset=1&cid={$main['srcID']}&oid={$main['dstID']}&action=update&rgid={$rgid}";
1067 if ($gid) {
1068 $mergeParams .= "&gid={$gid}";
1069 }
1070
1071 $searchRows[$mainId]['actions'] = CRM_Utils_System::href(ts('merge'), 'civicrm/contact/merge', $mergeParams);
1072 $searchRows[$mainId]['actions'] .= "&nbsp;|&nbsp; <a id='notDuplicate' href='#' onClick=\"processDupes( {$main['srcID']}, {$main['dstID']}, 'dupe-nondupe', 'dupe-listing'); return false;\">" . ts('not a duplicate') . "</a>";
1073 }
1074 else {
1075 $searchRows[$mainId]['actions'] = '<em>' . ts('Insufficient access rights - cannot merge') . '</em>';
1076 }
1077 }
1078
1079 echo CRM_Utils_JSON::encodeDataTableSelector($searchRows, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
1080
1081 CRM_Utils_System::civiExit();
1082 }
1083
1084 /**
1085 * Function to retrieve a PDF Page Format for the PDF Letter form
1086 */
1087 function pdfFormat() {
1088 $formatId = CRM_Utils_Type::escape($_REQUEST['formatId'], 'Integer');
1089
1090 $pdfFormat = CRM_Core_BAO_PdfFormat::getById($formatId);
1091
1092 echo json_encode($pdfFormat);
1093 CRM_Utils_System::civiExit();
1094 }
1095
1096 /**
1097 * Function to retrieve Paper Size dimensions
1098 */
1099 static function paperSize() {
1100 $paperSizeName = CRM_Utils_Type::escape($_REQUEST['paperSizeName'], 'String');
1101
1102 $paperSize = CRM_Core_BAO_PaperSize::getByName($paperSizeName);
1103
1104 echo json_encode($paperSize);
1105 CRM_Utils_System::civiExit();
1106 }
1107
1108 static function selectUnselectContacts() {
1109 $name = CRM_Utils_Array::value('name', $_REQUEST);
1110 $cacheKey = CRM_Utils_Array::value('qfKey', $_REQUEST);
1111 $state = CRM_Utils_Array::value('state', $_REQUEST, 'checked');
1112 $variableType = CRM_Utils_Array::value('variableType', $_REQUEST, 'single');
1113
1114 $actionToPerform = CRM_Utils_Array::value('action', $_REQUEST, 'select');
1115
1116 if ($variableType == 'multiple') {
1117 // action post value only works with multiple type variable
1118 if ($name) {
1119 //multiple names like mark_x_1-mark_x_2 where 1,2 are cids
1120 $elements = explode('-', $name);
1121 foreach ($elements as $key => $element) {
1122 $elements[$key] = self::_convertToId($element);
1123 }
1124 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $actionToPerform, $elements);
1125 }
1126 else {
1127 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $actionToPerform);
1128 }
1129 }
1130 elseif ($variableType == 'single') {
1131 $cId = self::_convertToId($name);
1132 $action = ($state == 'checked') ? 'select' : 'unselect';
1133 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $action, $cId);
1134 }
1135 $contactIds = CRM_Core_BAO_PrevNextCache::getSelection($cacheKey);
1136 $countSelectionCids = count($contactIds[$cacheKey]);
1137
1138 $arrRet = array('getCount' => $countSelectionCids);
1139 echo json_encode($arrRet);
1140 CRM_Utils_System::civiExit();
1141 }
1142
1143 static function _convertToId($name) {
1144 if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
1145 $cId = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
1146 }
1147 return $cId;
1148 }
1149
1150 static function getAddressDisplay() {
1151 $contactId = CRM_Utils_Array::value('contact_id', $_REQUEST);
1152 if (!$contactId) {
1153 $addressVal["error_message"] = "no contact id found";
1154 }
1155 else {
1156 $entityBlock =
1157 array(
1158 'contact_id' => $contactId,
1159 'entity_id' => $contactId,
1160 );
1161 $addressVal = CRM_Core_BAO_Address::getValues($entityBlock);
1162 }
1163
1164 echo json_encode($addressVal);
1165 CRM_Utils_System::civiExit();
1166 }
1167 }