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