Merge pull request #2995 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_Utils_Array::value('rowcount', $_GET, 20);
665
666 $offset = CRM_Utils_Type::escape($offset, 'Int');
667 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
668
669 // add acl clause here
670 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
671 if ($aclWhere) {
672 $aclWhere = " AND $aclWhere";
673 }
674 if ($noemail) {
675 $query = "
676 SELECT sort_name name, cc.id
677 FROM civicrm_contact cc
678 {$aclFrom}
679 WHERE cc.is_deceased = 0 AND {$queryString}
680 {$aclWhere}
681 LIMIT {$offset}, {$rowCount}
682 ";
683
684 // send query to hook to be modified if needed
685 CRM_Utils_Hook::contactListQuery($query,
686 $name,
687 CRM_Utils_Array::value('context', $_GET),
688 CRM_Utils_Array::value('cid', $_GET)
689 );
690
691 $dao = CRM_Core_DAO::executeQuery($query);
692 while ($dao->fetch()) {
693 $result[] = array(
694 'name' => $dao->name,
695 'id' => $dao->id,
696 );
697 }
698 }
699 else {
700 $query = "
701 SELECT sort_name name, ce.email, cc.id
702 FROM civicrm_email ce INNER JOIN civicrm_contact cc ON cc.id = ce.contact_id
703 {$aclFrom}
704 WHERE ce.on_hold = 0 AND cc.is_deceased = 0 AND cc.do_not_email = 0 AND {$queryString}
705 {$aclWhere}
706 LIMIT {$offset}, {$rowCount}
707 ";
708
709 // send query to hook to be modified if needed
710 CRM_Utils_Hook::contactListQuery($query,
711 $name,
712 CRM_Utils_Array::value('context', $_GET),
713 CRM_Utils_Array::value('cid', $_GET)
714 );
715
716
717 $dao = CRM_Core_DAO::executeQuery($query);
718
719 while ($dao->fetch()) {
720 $result[] = array(
721 'name' => '"' . $dao->name . '" &lt;' . $dao->email . '&gt;',
722 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->email}" : '"' . $dao->name . '" <' . $dao->email . '>',
723 );
724 }
725 }
726
727 if ($result) {
728 echo json_encode($result);
729 }
730 }
731 }
732 CRM_Utils_System::civiExit();
733 }
734
735 static function getContactPhone() {
736
737 $queryString = NULL;
738 //check for mobile type
739 $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
740 $mobileType = CRM_Utils_Array::value('Mobile', $phoneTypes);
741
742 $name = CRM_Utils_Array::value('name', $_GET);
743 if ($name) {
744 $name = CRM_Utils_Type::escape($name, 'String');
745 $queryString = " ( cc.sort_name LIKE '%$name%' OR cp.phone LIKE '%$name%' ) ";
746 }
747 else {
748 $cid = CRM_Utils_Array::value('cid', $_GET);
749 if ($cid) {
750 //check cid for interger
751 $contIDS = explode(',', $cid);
752 foreach ($contIDS as $contID) {
753 CRM_Utils_Type::escape($contID, 'Integer');
754 }
755 $queryString = " cc.id IN ( $cid )";
756 }
757 }
758
759 if ($queryString) {
760 $offset = CRM_Utils_Array::value('offset', $_GET, 0);
761 $rowCount = CRM_Utils_Array::value('rowcount', $_GET, 20);
762
763 $offset = CRM_Utils_Type::escape($offset, 'Int');
764 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
765
766 // add acl clause here
767 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
768 if ($aclWhere) {
769 $aclWhere = " AND $aclWhere";
770 }
771
772 $query = "
773 SELECT sort_name name, cp.phone, cc.id
774 FROM civicrm_phone cp INNER JOIN civicrm_contact cc ON cc.id = cp.contact_id
775 {$aclFrom}
776 WHERE cc.is_deceased = 0 AND cc.do_not_sms = 0 AND cp.phone_type_id = {$mobileType} AND {$queryString}
777 {$aclWhere}
778 LIMIT {$offset}, {$rowCount}
779 ";
780
781 // send query to hook to be modified if needed
782 CRM_Utils_Hook::contactListQuery($query,
783 $name,
784 CRM_Utils_Array::value('context', $_GET),
785 CRM_Utils_Array::value('cid', $_GET)
786 );
787
788 $dao = CRM_Core_DAO::executeQuery($query);
789
790 while ($dao->fetch()) {
791 $result[] = array(
792 'name' => '"' . $dao->name . '" &lt;' . $dao->phone . '&gt;',
793 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->phone}" : '"' . $dao->name . '" <' . $dao->phone . '>',
794 );
795 }
796 }
797
798 if ($result) {
799 echo json_encode($result);
800 }
801 CRM_Utils_System::civiExit();
802 }
803
804
805 static function buildSubTypes() {
806 $parent = CRM_Utils_Array::value('parentId', $_REQUEST);
807
808 switch ($parent) {
809 case 1:
810 $contactType = 'Individual';
811 break;
812
813 case 2:
814 $contactType = 'Household';
815 break;
816
817 case 4:
818 $contactType = 'Organization';
819 break;
820 }
821
822 $subTypes = CRM_Contact_BAO_ContactType::subTypePairs($contactType, FALSE, NULL);
823 asort($subTypes);
824 echo json_encode($subTypes);
825 CRM_Utils_System::civiExit();
826 }
827
828 static function buildDedupeRules() {
829 $parent = CRM_Utils_Array::value('parentId', $_REQUEST);
830
831 switch ($parent) {
832 case 1:
833 $contactType = 'Individual';
834 break;
835
836 case 2:
837 $contactType = 'Household';
838 break;
839
840 case 4:
841 $contactType = 'Organization';
842 break;
843 }
844
845 $dedupeRules = CRM_Dedupe_BAO_RuleGroup::getByType($contactType);
846
847 echo json_encode($dedupeRules);
848 CRM_Utils_System::civiExit();
849 }
850
851 /**
852 * Function used for CiviCRM dashboard operations
853 */
854 static function dashboard() {
855 $operation = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
856
857 switch ($operation) {
858 case 'get_widgets_by_column':
859 // This would normally be coming from either the database (this user's settings) or a default/initial dashboard configuration.
860 // get contact id of logged in user
861
862 $dashlets = CRM_Core_BAO_Dashboard::getContactDashlets();
863 break;
864
865 case 'get_widget':
866 $dashletID = CRM_Utils_Type::escape($_GET['id'], 'Positive');
867
868 $dashlets = CRM_Core_BAO_Dashboard::getDashletInfo($dashletID);
869 break;
870
871 case 'save_columns':
872 CRM_Core_BAO_Dashboard::saveDashletChanges($_REQUEST['columns']);
873 CRM_Utils_System::civiExit();
874 case 'delete_dashlet':
875 $dashletID = CRM_Utils_Type::escape($_REQUEST['dashlet_id'], 'Positive');
876 CRM_Core_BAO_Dashboard::deleteDashlet($dashletID);
877 CRM_Utils_System::civiExit();
878 }
879
880 echo json_encode($dashlets);
881 CRM_Utils_System::civiExit();
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 echo json_encode($signatures);
901 CRM_Utils_System::civiExit();
902 }
903
904 /**
905 * Function to process dupes.
906 *
907 */
908 static function processDupes() {
909 $oper = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
910 $cid = CRM_Utils_Type::escape($_REQUEST['cid'], 'Positive');
911 $oid = CRM_Utils_Type::escape($_REQUEST['oid'], 'Positive');
912
913 if (!$oper || !$cid || !$oid) {
914 return;
915 }
916
917 $exception = new CRM_Dedupe_DAO_Exception();
918 $exception->contact_id1 = $cid;
919 $exception->contact_id2 = $oid;
920 //make sure contact2 > contact1.
921 if ($cid > $oid) {
922 $exception->contact_id1 = $oid;
923 $exception->contact_id2 = $cid;
924 }
925 $exception->find(TRUE);
926 $status = NULL;
927 if ($oper == 'dupe-nondupe') {
928 $status = $exception->save();
929 }
930 if ($oper == 'nondupe-dupe') {
931 $status = $exception->delete();
932 }
933
934 echo json_encode(array('status' => ($status) ? $oper : $status));
935 CRM_Utils_System::civiExit();
936 }
937
938 static function getDedupes() {
939
940 $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
941 $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
942 $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
943 $sort = 'sort_name';
944 $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
945
946 $gid = isset($_REQUEST['gid']) ? CRM_Utils_Type::escape($_REQUEST['gid'], 'Integer') : 0;
947 $rgid = isset($_REQUEST['rgid']) ? CRM_Utils_Type::escape($_REQUEST['rgid'], 'Integer') : 0;
948 $contactType = '';
949 if ($rgid) {
950 $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
951 }
952
953 $cacheKeyString = "merge {$contactType}_{$rgid}_{$gid}";
954 $searchRows = array();
955 $selectorElements = array('src', 'dst', 'weight', 'actions');
956
957
958 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
959 pn.entity_id2 = de.contact_id2 )";
960 $where = "de.id IS NULL";
961
962 $iFilteredTotal = $iTotal = CRM_Core_BAO_PrevNextCache::getCount($cacheKeyString, $join, $where);
963 $mainContacts = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, $offset, $rowCount);
964
965 foreach ($mainContacts as $mainId => $main) {
966 $searchRows[$mainId]['src'] = CRM_Utils_System::href($main['srcName'], 'civicrm/contact/view', "reset=1&cid={$main['srcID']}");
967 $searchRows[$mainId]['dst'] = CRM_Utils_System::href($main['dstName'], 'civicrm/contact/view', "reset=1&cid={$main['dstID']}");
968 $searchRows[$mainId]['weight'] = CRM_Utils_Array::value('weight', $main);
969
970 if (!empty($main['canMerge'])) {
971 $mergeParams = "reset=1&cid={$main['srcID']}&oid={$main['dstID']}&action=update&rgid={$rgid}";
972 if ($gid) {
973 $mergeParams .= "&gid={$gid}";
974 }
975
976 $searchRows[$mainId]['actions'] = CRM_Utils_System::href(ts('merge'), 'civicrm/contact/merge', $mergeParams);
977 $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>";
978 }
979 else {
980 $searchRows[$mainId]['actions'] = '<em>' . ts('Insufficient access rights - cannot merge') . '</em>';
981 }
982 }
983
984 echo CRM_Utils_JSON::encodeDataTableSelector($searchRows, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
985
986 CRM_Utils_System::civiExit();
987 }
988
989 /**
990 * Function to retrieve a PDF Page Format for the PDF Letter form
991 */
992 function pdfFormat() {
993 $formatId = CRM_Utils_Type::escape($_REQUEST['formatId'], 'Integer');
994
995 $pdfFormat = CRM_Core_BAO_PdfFormat::getById($formatId);
996
997 echo json_encode($pdfFormat);
998 CRM_Utils_System::civiExit();
999 }
1000
1001 /**
1002 * Function to retrieve Paper Size dimensions
1003 */
1004 static function paperSize() {
1005 $paperSizeName = CRM_Utils_Type::escape($_REQUEST['paperSizeName'], 'String');
1006
1007 $paperSize = CRM_Core_BAO_PaperSize::getByName($paperSizeName);
1008
1009 echo json_encode($paperSize);
1010 CRM_Utils_System::civiExit();
1011 }
1012
1013 static function selectUnselectContacts() {
1014 $name = CRM_Utils_Array::value('name', $_REQUEST);
1015 $cacheKey = CRM_Utils_Array::value('qfKey', $_REQUEST);
1016 $state = CRM_Utils_Array::value('state', $_REQUEST, 'checked');
1017 $variableType = CRM_Utils_Array::value('variableType', $_REQUEST, 'single');
1018
1019 $actionToPerform = CRM_Utils_Array::value('action', $_REQUEST, 'select');
1020
1021 if ($variableType == 'multiple') {
1022 // action post value only works with multiple type variable
1023 if ($name) {
1024 //multiple names like mark_x_1-mark_x_2 where 1,2 are cids
1025 $elements = explode('-', $name);
1026 foreach ($elements as $key => $element) {
1027 $elements[$key] = self::_convertToId($element);
1028 }
1029 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $actionToPerform, $elements);
1030 }
1031 else {
1032 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $actionToPerform);
1033 }
1034 }
1035 elseif ($variableType == 'single') {
1036 $cId = self::_convertToId($name);
1037 $action = ($state == 'checked') ? 'select' : 'unselect';
1038 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $action, $cId);
1039 }
1040 $contactIds = CRM_Core_BAO_PrevNextCache::getSelection($cacheKey);
1041 $countSelectionCids = count($contactIds[$cacheKey]);
1042
1043 $arrRet = array('getCount' => $countSelectionCids);
1044 echo json_encode($arrRet);
1045 CRM_Utils_System::civiExit();
1046 }
1047
1048 static function _convertToId($name) {
1049 if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
1050 $cId = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
1051 }
1052 return $cId;
1053 }
1054
1055 static function getAddressDisplay() {
1056 $contactId = CRM_Utils_Array::value('contact_id', $_REQUEST);
1057 if (!$contactId) {
1058 $addressVal["error_message"] = "no contact id found";
1059 }
1060 else {
1061 $entityBlock =
1062 array(
1063 'contact_id' => $contactId,
1064 'entity_id' => $contactId,
1065 );
1066 $addressVal = CRM_Core_BAO_Address::getValues($entityBlock);
1067 }
1068
1069 echo json_encode($addressVal);
1070 CRM_Utils_System::civiExit();
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 $sortMapper = array(
1081 0 => 'relation',
1082 1 => 'sort_name',
1083 2 => 'start_date',
1084 3 => 'end_date',
1085 4 => 'city',
1086 5 => 'state',
1087 6 => 'email',
1088 7 => 'phone',
1089 8 => 'links',
1090 9 => '',
1091 10 => '',
1092 );
1093
1094 $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
1095 $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
1096 $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
1097 $sort = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL;
1098 $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
1099
1100 $params = $_POST;
1101 if ($sort && $sortOrder) {
1102 $params['sortBy'] = $sort . ' ' . $sortOrder;
1103 }
1104
1105 $params['page'] = ($offset / $rowCount) + 1;
1106 $params['rp'] = $rowCount;
1107
1108 $params['contact_id'] = $contactID;
1109 $params['context'] = $context;
1110
1111 // get the contact relationships
1112 $relationships = CRM_Contact_BAO_Relationship::getContactRelationshipSelector($params);
1113
1114 $iFilteredTotal = $iTotal = $params['total'];
1115 $selectorElements = array(
1116 'relation',
1117 'name',
1118 'start_date',
1119 'end_date',
1120 'city',
1121 'state',
1122 'email',
1123 'phone',
1124 'links',
1125 'id',
1126 'is_active',
1127 );
1128
1129 echo CRM_Utils_JSON::encodeDataTableSelector($relationships, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
1130 CRM_Utils_System::civiExit();
1131 }
1132 }