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