Merge pull request #4900 from mrpaulc/CRM-15806
[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_System::civiExit(json_encode($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 $gids = CRM_Utils_Type::escape($_GET['gids'], 'String');
334 echo CRM_Contact_BAO_GroupNestingCache::json($gids);
335 CRM_Utils_System::civiExit();
336 }
337
338 /**
339 * @deprecated
340 * Old quicksearch function. No longer used in core.
341 * @todo: Remove this function and associated menu entry in CiviCRM 5
342 */
343 static function search() {
344 $json = TRUE;
345 $name = CRM_Utils_Array::value('name', $_GET, '');
346 if (!array_key_exists('name', $_GET)) {
347 $name = CRM_Utils_Array::value('s', $_GET) . '%';
348 $json = FALSE;
349 }
350 $name = CRM_Utils_Type::escape($name, 'String');
351 $whereIdClause = '';
352 if (!empty($_GET['id'])) {
353 $json = TRUE;
354 if (is_numeric($_GET['id'])) {
355 $id = CRM_Utils_Type::escape($_GET['id'], 'Integer');
356 $whereIdClause = " AND civicrm_contact.id = {$id}";
357 }
358 else {
359 $name = $_GET['id'];
360 }
361 }
362
363 $elements = array();
364 if ($name || isset($id)) {
365 $name = $name . '%';
366
367 //contact's based of relationhip type
368 $relType = NULL;
369 if (isset($_GET['rel'])) {
370 $relation = explode('_', $_GET['rel']);
371 $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
372 $rel = CRM_Utils_Type::escape($relation[2], 'String');
373 }
374
375 //shared household info
376 $shared = NULL;
377 if (isset($_GET['sh'])) {
378 $shared = CRM_Utils_Type::escape($_GET['sh'], 'Integer');
379 if ($shared == 1) {
380 $contactType = 'Household';
381 $cName = 'household_name';
382 }
383 else {
384 $contactType = 'Organization';
385 $cName = 'organization_name';
386 }
387 }
388
389 // contacts of type household
390 $hh = $addStreet = $addCity = NULL;
391 if (isset($_GET['hh'])) {
392 $hh = CRM_Utils_Type::escape($_GET['hh'], 'Integer');
393 }
394
395 //organization info
396 $organization = $street = $city = NULL;
397 if (isset($_GET['org'])) {
398 $organization = CRM_Utils_Type::escape($_GET['org'], 'Integer');
399 }
400
401 if (isset($_GET['org']) || isset($_GET['hh'])) {
402 $json = FALSE;
403 $splitName = explode(' :: ', $name);
404 if ($splitName) {
405 $contactName = trim(CRM_Utils_Array::value('0', $splitName));
406 $street = trim(CRM_Utils_Array::value('1', $splitName));
407 $city = trim(CRM_Utils_Array::value('2', $splitName));
408 }
409 else {
410 $contactName = $name;
411 }
412
413 if ($street) {
414 $addStreet = "AND civicrm_address.street_address LIKE '$street%'";
415 }
416 if ($city) {
417 $addCity = "AND civicrm_address.city LIKE '$city%'";
418 }
419 }
420
421 if ($organization) {
422
423 $query = "
424 SELECT CONCAT_WS(' :: ',sort_name,LEFT(street_address,25),city) 'sort_name',
425 civicrm_contact.id 'id'
426 FROM civicrm_contact
427 LEFT JOIN civicrm_address ON ( civicrm_contact.id = civicrm_address.contact_id
428 AND civicrm_address.is_primary=1
429 )
430 WHERE civicrm_contact.contact_type='Organization' AND organization_name LIKE '%$contactName%'
431 {$addStreet} {$addCity} {$whereIdClause}
432 ORDER BY organization_name ";
433 }
434 elseif ($shared) {
435 $query = "
436 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} ";
437 }
438 elseif ($hh) {
439 $query = "
440 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'
441 FROM civicrm_contact
442 LEFT JOIN civicrm_address ON (civicrm_contact.id =civicrm_address.contact_id AND civicrm_address.is_primary =1 )
443 WHERE civicrm_contact.contact_type ='Household'
444 AND household_name LIKE '%$contactName%' {$addStreet} {$addCity} {$whereIdClause} ORDER BY household_name ";
445 }
446 elseif ($relType) {
447 if (!empty($_GET['case'])) {
448 $query = "
449 SELECT distinct(c.id), c.sort_name
450 FROM civicrm_contact c
451 LEFT JOIN civicrm_relationship ON civicrm_relationship.contact_id_{$rel} = c.id
452 WHERE c.sort_name LIKE '%$name%'
453 AND civicrm_relationship.relationship_type_id = $relType
454 GROUP BY sort_name
455 ";
456 }
457 }
458 else {
459
460 $query = "
461 SELECT sort_name, id
462 FROM civicrm_contact
463 WHERE sort_name LIKE '%$name'
464 {$whereIdClause}
465 ORDER BY sort_name ";
466 }
467
468 $limit = 10;
469 if (isset($_GET['limit'])) {
470 $limit = CRM_Utils_Type::escape($_GET['limit'], 'Positive');
471 }
472
473 $query .= " LIMIT 0,{$limit}";
474
475 $dao = CRM_Core_DAO::executeQuery($query);
476
477 if ($shared) {
478 while ($dao->fetch()) {
479 echo $dao->sort_name;
480 CRM_Utils_System::civiExit();
481 }
482 }
483 else {
484 while ($dao->fetch()) {
485 if ($json) {
486 $elements[] = array('name' => addslashes($dao->sort_name),
487 'id' => $dao->id,
488 );
489 }
490 else {
491 echo $elements = "$dao->sort_name|$dao->id|$dao->location_type_id|$dao->is_primary|$dao->is_billing\n";
492 }
493 }
494 //for adding new household address / organization
495 if (empty($elements) && !$json && ($hh || $organization)) {
496 echo CRM_Utils_Array::value('s', $_GET);
497 }
498 }
499 }
500
501 if (isset($_GET['sh'])) {
502 echo "";
503 CRM_Utils_System::civiExit();
504 }
505
506 if (empty($elements)) {
507 $name = str_replace('%', '', $name);
508 $elements[] = array(
509 'name' => $name,
510 'id' => $name,
511 );
512 }
513
514 if ($json) {
515 echo json_encode($elements);
516 }
517 CRM_Utils_System::civiExit();
518 }
519
520 /**
521 * Function to delete custom value
522 *
523 */
524 static function deleteCustomValue() {
525 $customValueID = CRM_Utils_Type::escape($_REQUEST['valueID'], 'Positive');
526 $customGroupID = CRM_Utils_Type::escape($_REQUEST['groupID'], 'Positive');
527
528 CRM_Core_BAO_CustomValue::deleteCustomValue($customValueID, $customGroupID);
529 $contactId = CRM_Utils_Array::value('contactId', $_REQUEST);
530 if ($contactId) {
531 echo CRM_Contact_BAO_Contact::getCountComponent('custom_' . $_REQUEST['groupID'], $contactId);
532 }
533
534 // reset the group contact cache for this group
535 CRM_Contact_BAO_GroupContactCache::remove();
536 CRM_Utils_System::civiExit();
537 }
538
539 /**
540 * Function to perform enable / disable actions on record.
541 *
542 */
543 static function enableDisable() {
544 $op = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
545 $recordID = CRM_Utils_Type::escape($_REQUEST['recordID'], 'Positive');
546 $recordBAO = CRM_Utils_Type::escape($_REQUEST['recordBAO'], 'String');
547
548 $isActive = NULL;
549 if ($op == 'disable-enable') {
550 $isActive = TRUE;
551 }
552 elseif ($op == 'enable-disable') {
553 $isActive = FALSE;
554 }
555 $status = array('status' => 'record-updated-fail');
556 if (isset($isActive)) {
557 // first munge and clean the recordBAO and get rid of any non alpha numeric characters
558 $recordBAO = CRM_Utils_String::munge($recordBAO);
559 $recordClass = explode('_', $recordBAO);
560
561 // make sure recordClass is namespaced (we cant check CRM since extensions can also use this)
562 // but it should be at least 3 levels deep
563 if (count($recordClass) >= 3) {
564 require_once (str_replace('_', DIRECTORY_SEPARATOR, $recordBAO) . ".php");
565 $method = 'setIsActive';
566
567 if (method_exists($recordBAO, $method)) {
568 $updated = call_user_func_array(array($recordBAO, $method),
569 array($recordID, $isActive)
570 );
571 if ($updated) {
572 $status = array('status' => 'record-updated-success');
573 }
574
575 // call hook enableDisable
576 CRM_Utils_Hook::enableDisable($recordBAO, $recordID, $isActive);
577 }
578 }
579 CRM_Utils_JSON::output($status);
580 }
581 }
582
583 /**
584 *Function to check the CMS username
585 *
586 */
587 static public function checkUserName() {
588 $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), array('for', 'ts'));
589 if (
590 CRM_Utils_Time::getTimeRaw() > $_REQUEST['ts'] + self::CHECK_USERNAME_TTL
591 || $_REQUEST['for'] != 'civicrm/ajax/cmsuser'
592 || !$signer->validate($_REQUEST['sig'], $_REQUEST)
593 ) {
594 $user = array('name' => 'error');
595 echo json_encode($user);
596 CRM_Utils_System::civiExit();
597 }
598
599 $config = CRM_Core_Config::singleton();
600 $username = trim($_REQUEST['cms_name']);
601
602 $params = array('name' => $username);
603
604 $errors = array();
605 $config->userSystem->checkUserNameEmailExists($params, $errors);
606
607 if (isset($errors['cms_name']) || isset($errors['name'])) {
608 //user name is not availble
609 $user = array('name' => 'no');
610 echo json_encode($user);
611 }
612 else {
613 //user name is available
614 $user = array('name' => 'yes');
615 echo json_encode($user);
616 }
617 CRM_Utils_System::civiExit();
618 }
619
620 /**
621 * Function to get email address of a contact
622 */
623 static function getContactEmail() {
624 if (!empty($_REQUEST['contact_id'])) {
625 $contactID = CRM_Utils_Type::escape($_REQUEST['contact_id'], 'Positive');
626 if (!CRM_Contact_BAO_Contact_Permission::allow($contactID, CRM_Core_Permission::EDIT)) {
627 return;
628 }
629 list($displayName,
630 $userEmail
631 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
632 if ($userEmail) {
633 echo $userEmail;
634 }
635 }
636 else {
637 $noemail = CRM_Utils_Array::value('noemail', $_GET);
638 $queryString = NULL;
639 $name = CRM_Utils_Array::value('name', $_GET);
640 if ($name) {
641 $name = CRM_Utils_Type::escape($name, 'String');
642 if ($noemail) {
643 $queryString = " cc.sort_name LIKE '%$name%'";
644 }
645 else {
646 $queryString = " ( cc.sort_name LIKE '%$name%' OR ce.email LIKE '%$name%' ) ";
647 }
648 }
649 else {
650 $cid = CRM_Utils_Array::value('cid', $_GET);
651 if ($cid) {
652 //check cid for interger
653 $contIDS = explode(',', $cid);
654 foreach ($contIDS as $contID) {
655 CRM_Utils_Type::escape($contID, 'Integer');
656 }
657 $queryString = " cc.id IN ( $cid )";
658 }
659 }
660
661 if ($queryString) {
662 $offset = CRM_Utils_Array::value('offset', $_GET, 0);
663 $rowCount = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'search_autocomplete_count', NULL, 10);
664
665 $offset = CRM_Utils_Type::escape($offset, 'Int');
666
667 // add acl clause here
668 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
669 if ($aclWhere) {
670 $aclWhere = " AND $aclWhere";
671 }
672 if ($noemail) {
673 $query = "
674 SELECT sort_name name, cc.id
675 FROM civicrm_contact cc
676 {$aclFrom}
677 WHERE cc.is_deceased = 0 AND {$queryString}
678 {$aclWhere}
679 LIMIT {$offset}, {$rowCount}
680 ";
681
682 // send query to hook to be modified if needed
683 CRM_Utils_Hook::contactListQuery($query,
684 $name,
685 CRM_Utils_Array::value('context', $_GET),
686 CRM_Utils_Array::value('cid', $_GET)
687 );
688
689 $dao = CRM_Core_DAO::executeQuery($query);
690 while ($dao->fetch()) {
691 $result[] = array(
692 'id' => $dao->id,
693 'text' => $dao->name,
694 );
695 }
696 }
697 else {
698 $query = "
699 SELECT sort_name name, ce.email, cc.id
700 FROM civicrm_email ce INNER JOIN civicrm_contact cc ON cc.id = ce.contact_id
701 {$aclFrom}
702 WHERE ce.on_hold = 0 AND cc.is_deceased = 0 AND cc.do_not_email = 0 AND {$queryString}
703 {$aclWhere}
704 LIMIT {$offset}, {$rowCount}
705 ";
706
707 // send query to hook to be modified if needed
708 CRM_Utils_Hook::contactListQuery($query,
709 $name,
710 CRM_Utils_Array::value('context', $_GET),
711 CRM_Utils_Array::value('cid', $_GET)
712 );
713
714
715 $dao = CRM_Core_DAO::executeQuery($query);
716
717 while ($dao->fetch()) {
718 //working here
719 $result[] = array(
720 'text' => '"' . $dao->name . '" <' . $dao->email . '>',
721 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->email}" : '"' . $dao->name . '" <' . $dao->email . '>',
722 );
723 }
724 }
725 if ($result) {
726 echo json_encode($result);
727 }
728 }
729 }
730 CRM_Utils_System::civiExit();
731 }
732
733 static function getContactPhone() {
734
735 $queryString = NULL;
736 //check for mobile type
737 $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
738 $mobileType = CRM_Utils_Array::value('Mobile', $phoneTypes);
739
740 $name = CRM_Utils_Array::value('name', $_GET);
741 if ($name) {
742 $name = CRM_Utils_Type::escape($name, 'String');
743 $queryString = " ( cc.sort_name LIKE '%$name%' OR cp.phone LIKE '%$name%' ) ";
744 }
745 else {
746 $cid = CRM_Utils_Array::value('cid', $_GET);
747 if ($cid) {
748 //check cid for interger
749 $contIDS = explode(',', $cid);
750 foreach ($contIDS as $contID) {
751 CRM_Utils_Type::escape($contID, 'Integer');
752 }
753 $queryString = " cc.id IN ( $cid )";
754 }
755 }
756
757 if ($queryString) {
758 $offset = CRM_Utils_Array::value('offset', $_GET, 0);
759 $rowCount = CRM_Utils_Array::value('rowcount', $_GET, 20);
760
761 $offset = CRM_Utils_Type::escape($offset, 'Int');
762 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
763
764 // add acl clause here
765 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
766 if ($aclWhere) {
767 $aclWhere = " AND $aclWhere";
768 }
769
770 $query = "
771 SELECT sort_name name, cp.phone, cc.id
772 FROM civicrm_phone cp INNER JOIN civicrm_contact cc ON cc.id = cp.contact_id
773 {$aclFrom}
774 WHERE cc.is_deceased = 0 AND cc.do_not_sms = 0 AND cp.phone_type_id = {$mobileType} AND {$queryString}
775 {$aclWhere}
776 LIMIT {$offset}, {$rowCount}
777 ";
778
779 // send query to hook to be modified if needed
780 CRM_Utils_Hook::contactListQuery($query,
781 $name,
782 CRM_Utils_Array::value('context', $_GET),
783 CRM_Utils_Array::value('cid', $_GET)
784 );
785
786 $dao = CRM_Core_DAO::executeQuery($query);
787
788 while ($dao->fetch()) {
789 $result[] = array(
790 'text' => '"' . $dao->name . '" (' . $dao->phone . ')',
791 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->phone}" : '"' . $dao->name . '" <' . $dao->phone . '>',
792 );
793 }
794 }
795
796 if ($result) {
797 echo json_encode($result);
798 }
799 CRM_Utils_System::civiExit();
800 }
801
802
803 static function buildSubTypes() {
804 $parent = CRM_Utils_Array::value('parentId', $_REQUEST);
805
806 switch ($parent) {
807 case 1:
808 $contactType = 'Individual';
809 break;
810
811 case 2:
812 $contactType = 'Household';
813 break;
814
815 case 4:
816 $contactType = 'Organization';
817 break;
818 }
819
820 $subTypes = CRM_Contact_BAO_ContactType::subTypePairs($contactType, FALSE, NULL);
821 asort($subTypes);
822 CRM_Utils_JSON::output($subTypes);
823 }
824
825 static function buildDedupeRules() {
826 $parent = CRM_Utils_Array::value('parentId', $_REQUEST);
827
828 switch ($parent) {
829 case 1:
830 $contactType = 'Individual';
831 break;
832
833 case 2:
834 $contactType = 'Household';
835 break;
836
837 case 4:
838 $contactType = 'Organization';
839 break;
840 }
841
842 $dedupeRules = CRM_Dedupe_BAO_RuleGroup::getByType($contactType);
843
844 CRM_Utils_JSON::output($dedupeRules);
845 }
846
847 /**
848 * Function used for CiviCRM dashboard operations
849 */
850 static function dashboard() {
851 $operation = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
852
853 switch ($operation) {
854 case 'get_widgets_by_column':
855 // This would normally be coming from either the database (this user's settings) or a default/initial dashboard configuration.
856 // get contact id of logged in user
857
858 $dashlets = CRM_Core_BAO_Dashboard::getContactDashlets();
859 break;
860
861 case 'get_widget':
862 $dashletID = CRM_Utils_Type::escape($_GET['id'], 'Positive');
863
864 $dashlets = CRM_Core_BAO_Dashboard::getDashletInfo($dashletID);
865 break;
866
867 case 'save_columns':
868 CRM_Core_BAO_Dashboard::saveDashletChanges($_REQUEST['columns']);
869 CRM_Utils_System::civiExit();
870 case 'delete_dashlet':
871 $dashletID = CRM_Utils_Type::escape($_REQUEST['dashlet_id'], 'Positive');
872 CRM_Core_BAO_Dashboard::deleteDashlet($dashletID);
873 CRM_Utils_System::civiExit();
874 }
875
876 CRM_Utils_JSON::output($dashlets);
877 }
878
879 /**
880 * Function to retrieve signature based on email id
881 */
882 static function getSignature() {
883 $emailID = CRM_Utils_Type::escape($_REQUEST['emailID'], 'Positive');
884 $query = "SELECT signature_text, signature_html FROM civicrm_email WHERE id = {$emailID}";
885 $dao = CRM_Core_DAO::executeQuery($query);
886
887 $signatures = array();
888 while ($dao->fetch()) {
889 $signatures = array(
890 'signature_text' => $dao->signature_text,
891 'signature_html' => $dao->signature_html,
892 );
893 }
894
895 CRM_Utils_JSON::output($signatures);
896 }
897
898 /**
899 * Function to process dupes.
900 *
901 */
902 static function processDupes() {
903 $oper = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
904 $cid = CRM_Utils_Type::escape($_REQUEST['cid'], 'Positive');
905 $oid = CRM_Utils_Type::escape($_REQUEST['oid'], 'Positive');
906
907 if (!$oper || !$cid || !$oid) {
908 return;
909 }
910
911 $exception = new CRM_Dedupe_DAO_Exception();
912 $exception->contact_id1 = $cid;
913 $exception->contact_id2 = $oid;
914 //make sure contact2 > contact1.
915 if ($cid > $oid) {
916 $exception->contact_id1 = $oid;
917 $exception->contact_id2 = $cid;
918 }
919 $exception->find(TRUE);
920 $status = NULL;
921 if ($oper == 'dupe-nondupe') {
922 $status = $exception->save();
923 }
924 if ($oper == 'nondupe-dupe') {
925 $status = $exception->delete();
926 }
927
928 CRM_Utils_JSON::output(array('status' => ($status) ? $oper : $status));
929 }
930
931 static function getDedupes() {
932
933 $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
934 $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
935 $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
936 $sort = 'sort_name';
937 $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
938
939 $gid = isset($_REQUEST['gid']) ? CRM_Utils_Type::escape($_REQUEST['gid'], 'Integer') : 0;
940 $rgid = isset($_REQUEST['rgid']) ? CRM_Utils_Type::escape($_REQUEST['rgid'], 'Integer') : 0;
941 $contactType = '';
942 if ($rgid) {
943 $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
944 }
945
946 $cacheKeyString = "merge {$contactType}_{$rgid}_{$gid}";
947 $searchRows = array();
948 $selectorElements = array('src', 'dst', 'weight', 'actions');
949
950
951 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
952 pn.entity_id2 = de.contact_id2 )";
953 $where = "de.id IS NULL";
954
955 $iFilteredTotal = $iTotal = CRM_Core_BAO_PrevNextCache::getCount($cacheKeyString, $join, $where);
956 $mainContacts = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, $offset, $rowCount);
957
958 foreach ($mainContacts as $mainId => $main) {
959 $searchRows[$mainId]['src'] = CRM_Utils_System::href($main['srcName'], 'civicrm/contact/view', "reset=1&cid={$main['srcID']}");
960 $searchRows[$mainId]['dst'] = CRM_Utils_System::href($main['dstName'], 'civicrm/contact/view', "reset=1&cid={$main['dstID']}");
961 $searchRows[$mainId]['weight'] = CRM_Utils_Array::value('weight', $main);
962
963 if (!empty($main['canMerge'])) {
964 $mergeParams = "reset=1&cid={$main['srcID']}&oid={$main['dstID']}&action=update&rgid={$rgid}";
965 if ($gid) {
966 $mergeParams .= "&gid={$gid}";
967 }
968
969 $searchRows[$mainId]['actions'] = CRM_Utils_System::href(ts('merge'), 'civicrm/contact/merge', $mergeParams);
970 $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>";
971 }
972 else {
973 $searchRows[$mainId]['actions'] = '<em>' . ts('Insufficient access rights - cannot merge') . '</em>';
974 }
975 }
976
977 echo CRM_Utils_JSON::encodeDataTableSelector($searchRows, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
978
979 CRM_Utils_System::civiExit();
980 }
981
982 /**
983 * Function to retrieve a PDF Page Format for the PDF Letter form
984 */
985 function pdfFormat() {
986 $formatId = CRM_Utils_Type::escape($_REQUEST['formatId'], 'Integer');
987
988 $pdfFormat = CRM_Core_BAO_PdfFormat::getById($formatId);
989
990 CRM_Utils_JSON::output($pdfFormat);
991 }
992
993 /**
994 * Function to retrieve Paper Size dimensions
995 */
996 static function paperSize() {
997 $paperSizeName = CRM_Utils_Type::escape($_REQUEST['paperSizeName'], 'String');
998
999 $paperSize = CRM_Core_BAO_PaperSize::getByName($paperSizeName);
1000
1001 CRM_Utils_JSON::output($paperSize);
1002 }
1003
1004 static function selectUnselectContacts() {
1005 $name = CRM_Utils_Array::value('name', $_REQUEST);
1006 $cacheKey = CRM_Utils_Array::value('qfKey', $_REQUEST);
1007 $state = CRM_Utils_Array::value('state', $_REQUEST, 'checked');
1008 $variableType = CRM_Utils_Array::value('variableType', $_REQUEST, 'single');
1009
1010 $actionToPerform = CRM_Utils_Array::value('action', $_REQUEST, 'select');
1011
1012 if ($variableType == 'multiple') {
1013 // action post value only works with multiple type variable
1014 if ($name) {
1015 //multiple names like mark_x_1-mark_x_2 where 1,2 are cids
1016 $elements = explode('-', $name);
1017 foreach ($elements as $key => $element) {
1018 $elements[$key] = self::_convertToId($element);
1019 }
1020 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $actionToPerform, $elements);
1021 }
1022 else {
1023 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $actionToPerform);
1024 }
1025 }
1026 elseif ($variableType == 'single') {
1027 $cId = self::_convertToId($name);
1028 $action = ($state == 'checked') ? 'select' : 'unselect';
1029 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $action, $cId);
1030 }
1031 $contactIds = CRM_Core_BAO_PrevNextCache::getSelection($cacheKey);
1032 $countSelectionCids = count($contactIds[$cacheKey]);
1033
1034 $arrRet = array('getCount' => $countSelectionCids);
1035 CRM_Utils_JSON::output($arrRet);
1036 }
1037
1038 /**
1039 * @param $name
1040 *
1041 * @return string
1042 */
1043 static function _convertToId($name) {
1044 if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
1045 $cId = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
1046 }
1047 return $cId;
1048 }
1049
1050 static function getAddressDisplay() {
1051 $contactId = CRM_Utils_Array::value('contact_id', $_REQUEST);
1052 if (!$contactId) {
1053 $addressVal["error_message"] = "no contact id found";
1054 }
1055 else {
1056 $entityBlock =
1057 array(
1058 'contact_id' => $contactId,
1059 'entity_id' => $contactId,
1060 );
1061 $addressVal = CRM_Core_BAO_Address::getValues($entityBlock);
1062 }
1063
1064 CRM_Utils_JSON::output($addressVal);
1065 }
1066
1067 /**
1068 * Function to retrieve contact relationships
1069 */
1070 public static function getContactRelationships() {
1071 $contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
1072 $context = CRM_Utils_Type::escape($_GET['context'], 'String');
1073
1074 $sortMapper = array(
1075 0 => 'relation',
1076 1 => 'sort_name',
1077 2 => 'start_date',
1078 3 => 'end_date',
1079 4 => 'city',
1080 5 => 'state',
1081 6 => 'email',
1082 7 => 'phone',
1083 8 => 'links',
1084 9 => '',
1085 10 => '',
1086 );
1087
1088 $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
1089 $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
1090 $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
1091 $sort = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL;
1092 $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
1093
1094 $params = $_POST;
1095 if ($sort && $sortOrder) {
1096 $params['sortBy'] = $sort . ' ' . $sortOrder;
1097 }
1098
1099 $params['page'] = ($offset / $rowCount) + 1;
1100 $params['rp'] = $rowCount;
1101
1102 $params['contact_id'] = $contactID;
1103 $params['context'] = $context;
1104
1105 // get the contact relationships
1106 $relationships = CRM_Contact_BAO_Relationship::getContactRelationshipSelector($params);
1107
1108 $iFilteredTotal = $iTotal = $params['total'];
1109 $selectorElements = array(
1110 'relation',
1111 'name',
1112 'start_date',
1113 'end_date',
1114 'city',
1115 'state',
1116 'email',
1117 'phone',
1118 'links',
1119 'id',
1120 'is_active',
1121 );
1122
1123 echo CRM_Utils_JSON::encodeDataTableSelector($relationships, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
1124 CRM_Utils_System::civiExit();
1125 }
1126 }