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