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