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