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