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