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