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