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