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