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