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