INFRA-132 - Civi - PHPStorm cleanup
[civicrm-core.git] / CRM / Campaign / BAO / Survey.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35require_once 'CRM/Campaign/DAO/Survey.php';
4c6ce474
EM
36
37/**
38 * Class CRM_Campaign_BAO_Survey
39 */
6a488035
TO
40class CRM_Campaign_BAO_Survey extends CRM_Campaign_DAO_Survey {
41
42 /**
43 * Takes a bunch of params that are needed to match certain criteria and
44 * retrieves the relevant objects. Typically the valid params are only
45 * campaign_id.
46 *
7aaf6db0
TO
47 * @param array $params
48 * (reference ) an assoc array of name/value pairs.
49 * @param array $defaults
50 * (reference ) an assoc array to hold the flattened values.
6a488035
TO
51 */
52
53 /**
54 * The action links that we need to display for the browse screen
55 *
c490a46a 56 * @param array $params
77b97be7
EM
57 * @param $defaults
58 *
c490a46a 59 * @return CRM_Campaign_DAO_Survey|null
6a488035 60 */
00be9182 61 public static function retrieve(&$params, &$defaults) {
6a488035
TO
62 $dao = new CRM_Campaign_DAO_Survey();
63
64 $dao->copyValues($params);
65
66 if ($dao->find(TRUE)) {
67 CRM_Core_DAO::storeValues($dao, $defaults);
68 return $dao;
69 }
70 return NULL;
71 }
72
73 /**
100fef9d 74 * Takes an associative array and creates a Survey object
6a488035
TO
75 *
76 * the function extract all the params it needs to initialize the create a
77 * survey object.
78 *
79 *
c490a46a 80 * @param array $params
77b97be7 81 *
c490a46a 82 * @return CRM_Survey_DAO_Survey object
6a488035
TO
83 * @static
84 */
00be9182 85 public static function create(&$params) {
6a488035 86 if (empty($params)) {
5c2ea586 87 return FALSE;
6a488035
TO
88 }
89
a7488080 90 if (!empty($params['is_default'])) {
6a488035
TO
91 $query = "UPDATE civicrm_survey SET is_default = 0";
92 CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
93 }
94
95 if (!(CRM_Utils_Array::value('id', $params))) {
96
97 if (!(CRM_Utils_Array::value('created_id', $params))) {
98 $session = CRM_Core_Session::singleton();
99 $params['created_id'] = $session->get('userID');
100 }
101 if (!(CRM_Utils_Array::value('created_date', $params))) {
102 $params['created_date'] = date('YmdHis');
103 }
104 }
105
106 $dao = new CRM_Campaign_DAO_Survey();
107 $dao->copyValues($params);
108 $dao->save();
109
a7488080 110 if (!empty($params['custom']) &&
6a488035
TO
111 is_array($params['custom'])
112 ) {
113 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_survey', $dao->id);
114 }
115 return $dao;
116 }
117
118 /**
100fef9d 119 * Retrieve surveys for dashboard.
6a488035
TO
120 *
121 * @static
122 */
00be9182 123 public static function getSurveySummary($params = array(), $onlyCount = FALSE) {
6a488035
TO
124 //build the limit and order clause.
125 $limitClause = $orderByClause = $lookupTableJoins = NULL;
126 if (!$onlyCount) {
127 $sortParams = array(
128 'sort' => 'created_date',
129 'offset' => 0,
130 'rowCount' => 10,
131 'sortOrder' => 'desc',
132 );
133 foreach ($sortParams as $name => $default) {
a7488080 134 if (!empty($params[$name])) {
6a488035
TO
135 $sortParams[$name] = $params[$name];
136 }
137 }
138
139 //need to lookup tables.
140 $orderOnSurveyTable = TRUE;
141 if ($sortParams['sort'] == 'campaign') {
142 $orderOnSurveyTable = FALSE;
143 $lookupTableJoins = '
144 LEFT JOIN civicrm_campaign campaign ON ( campaign.id = survey.campaign_id )';
145 $orderByClause = "ORDER BY campaign.title {$sortParams['sortOrder']}";
146 }
147 elseif ($sortParams['sort'] == 'activity_type') {
148 $orderOnSurveyTable = FALSE;
149 $lookupTableJoins = "
91da6cd5 150 LEFT JOIN civicrm_option_value activity_type ON ( activity_type.value = survey.activity_type_id
6a488035
TO
151 OR survey.activity_type_id IS NULL )
152INNER JOIN civicrm_option_group grp ON ( activity_type.option_group_id = grp.id AND grp.name = 'activity_type' )";
153 $orderByClause = "ORDER BY activity_type.label {$sortParams['sortOrder']}";
154 }
155 elseif ($sortParams['sort'] == 'isActive') {
156 $sortParams['sort'] = 'is_active';
157 }
158 if ($orderOnSurveyTable) {
159 $orderByClause = "ORDER BY survey.{$sortParams['sort']} {$sortParams['sortOrder']}";
160 }
161 $limitClause = "LIMIT {$sortParams['offset']}, {$sortParams['rowCount']}";
162 }
163
164 //build the where clause.
165 $queryParams = $where = array();
166
167 //we only have activity type as a
168 //difference between survey and petition.
169 $petitionTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'petition', 'name');
170 if ($petitionTypeID) {
171 $where[] = "( survey.activity_type_id != %1 )";
172 $queryParams[1] = array($petitionTypeID, 'Positive');
173 }
174
a7488080 175 if (!empty($params['title'])) {
6a488035
TO
176 $where[] = "( survey.title LIKE %2 )";
177 $queryParams[2] = array('%' . trim($params['title']) . '%', 'String');
178 }
a7488080 179 if (!empty($params['campaign_id'])) {
6a488035
TO
180 $where[] = '( survey.campaign_id = %3 )';
181 $queryParams[3] = array($params['campaign_id'], 'Positive');
182 }
a7488080 183 if (!empty($params['activity_type_id'])) {
6a488035
TO
184 $typeId = $params['activity_type_id'];
185 if (is_array($params['activity_type_id'])) {
186 $typeId = implode(' , ', $params['activity_type_id']);
187 }
188 $where[] = "( survey.activity_type_id IN ( {$typeId} ) )";
189 }
190 $whereClause = NULL;
191 if (!empty($where)) {
192 $whereClause = ' WHERE ' . implode(" \nAND ", $where);
193 }
194
195 $selectClause = '
196SELECT survey.id as id,
197 survey.title as title,
198 survey.is_active as is_active,
199 survey.result_id as result_id,
200 survey.is_default as is_default,
201 survey.campaign_id as campaign_id,
202 survey.activity_type_id as activity_type_id,
203 survey.release_frequency as release_frequency,
204 survey.max_number_of_contacts as max_number_of_contacts,
205 survey.default_number_of_contacts as default_number_of_contacts';
206 if ($onlyCount) {
207 $selectClause = 'SELECT COUNT(*)';
208 }
209 $fromClause = 'FROM civicrm_survey survey';
210
211 $query = "{$selectClause} {$fromClause} {$lookupTableJoins} {$whereClause} {$orderByClause} {$limitClause}";
212
213 //return only count.
214 if ($onlyCount) {
5c2ea586 215 return (int) CRM_Core_DAO::singleValueQuery($query, $queryParams);
6a488035
TO
216 }
217
218 $surveys = array();
219 $properties = array(
220 'id', 'title', 'campaign_id', 'is_active', 'is_default', 'result_id', 'activity_type_id',
221 'release_frequency', 'max_number_of_contacts', 'default_number_of_contacts',
222 );
223
224 $survey = CRM_Core_DAO::executeQuery($query, $queryParams);
225 while ($survey->fetch()) {
226 foreach ($properties as $property) {
227 $surveys[$survey->id][$property] = $survey->$property;
228 }
229 }
230
231 return $surveys;
232 }
233
234 /**
235 * Get the survey count.
236 *
237 * @static
238 */
00be9182 239 public static function getSurveyCount() {
5c2ea586 240 return (int) CRM_Core_DAO::singleValueQuery('SELECT COUNT(*) FROM civicrm_survey');
6a488035
TO
241 }
242
243 /**
100fef9d 244 * Get Surveys
6a488035 245 *
7aaf6db0
TO
246 * @param bool $onlyActive
247 * Retrieve only active surveys.
248 * @param bool $onlyDefault
249 * Retrieve only default survey.
250 * @param bool $forceAll
251 * Retrieve all surveys.
252 * @param bool $includePetition
253 * Include or exclude petitions.
6a488035
TO
254 *
255 * @static
256 */
5c2ea586 257 public static function getSurveys($onlyActive = TRUE, $onlyDefault = FALSE, $forceAll = FALSE, $includePetition = FALSE) {
6a488035 258 $cacheKey = 0;
9231464f 259 $cacheKeyParams = array('onlyActive', 'onlyDefault', 'forceAll', 'includePetition');
6a488035
TO
260 foreach ($cacheKeyParams as $param) {
261 $cacheParam = $$param;
262 if (!$cacheParam) {
263 $cacheParam = 0;
264 }
265 $cacheKey .= '_' . $cacheParam;
266 }
267
268 static $surveys;
269
270 if (!isset($surveys[$cacheKey])) {
9231464f
KJ
271 if (!$includePetition) {
272 //we only have activity type as a
273 //difference between survey and petition.
274 $petitionTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'petition', 'name');
6a488035 275
9231464f
KJ
276 $where = array();
277 if ($petitionTypeID) {
278 $where[] = "( survey.activity_type_id != {$petitionTypeID} )";
279 }
6a488035
TO
280 }
281 if (!$forceAll && $onlyActive) {
282 $where[] = '( survey.is_active = 1 )';
283 }
284 if (!$forceAll && $onlyDefault) {
285 $where[] = '( survey.is_default = 1 )';
286 }
287 $whereClause = implode(' AND ', $where);
288
289 $query = "
290SELECT survey.id as id,
291 survey.title as title
292 FROM civicrm_survey as survey
293 WHERE {$whereClause}";
294 $surveys[$cacheKey] = array();
295 $survey = CRM_Core_DAO::executeQuery($query);
296 while ($survey->fetch()) {
297 $surveys[$cacheKey][$survey->id] = $survey->title;
298 }
299 }
300
301 return $surveys[$cacheKey];
302 }
303
304 /**
100fef9d 305 * Get Surveys activity types
6a488035
TO
306 *
307 *
308 * @static
309 */
5c2ea586
TO
310 static function getSurveyActivityType(
311 $returnColumn = 'label',
6a488035
TO
312 $includePetitionActivityType = FALSE
313 ) {
314 static $activityTypes;
315 $cacheKey = "{$returnColumn}_{$includePetitionActivityType}";
316
317 if (!isset($activityTypes[$cacheKey])) {
318 $activityTypes = array();
319 $campaignCompId = CRM_Core_Component::getComponentID('CiviCampaign');
320 if ($campaignCompId) {
321 $condition = " AND v.component_id={$campaignCompId}";
322 if (!$includePetitionActivityType) {
323 $condition .= " AND v.name != 'Petition'";
324 }
325 $activityTypes[$cacheKey] = CRM_Core_OptionGroup::values('activity_type',
326 FALSE, FALSE, FALSE,
327 $condition,
328 $returnColumn
329 );
330 }
331 }
7b60d5b9 332 if (!empty($activityTypes[$cacheKey])) {
333 return $activityTypes[$cacheKey];
334 }
335 else {
336 return;
337 }
6a488035
TO
338 }
339
340 /**
100fef9d 341 * Get Surveys custom groups
6a488035 342 *
5a4f6742
CW
343 * @param array $surveyTypes
344 * an array of survey type id.
6a488035 345 *
77b97be7 346 * @return array
6a488035
TO
347 * @static
348 */
00be9182 349 public static function getSurveyCustomGroups($surveyTypes = array()) {
6a488035
TO
350 $customGroups = array();
351 if (!is_array($surveyTypes)) {
352 $surveyTypes = array($surveyTypes);
353 }
354
355 if (!empty($surveyTypes)) {
356 $activityTypes = array_flip($surveyTypes);
357 }
358 else {
359 $activityTypes = self::getSurveyActivityType();
360 }
361
362 if (!empty($activityTypes)) {
363 $extendSubType = implode('[[:>:]]|[[:<:]]', array_keys($activityTypes));
364
365 $query = "SELECT cg.id, cg.name, cg.title, cg.extends_entity_column_value
366 FROM civicrm_custom_group cg
367 WHERE cg.is_active = 1 AND cg.extends_entity_column_value REGEXP '[[:<:]]{$extendSubType}[[:>:]]'";
368
369 $dao = CRM_Core_DAO::executeQuery($query);
370 while ($dao->fetch()) {
371 $customGroups[$dao->id]['id'] = $dao->id;
372 $customGroups[$dao->id]['name'] = $dao->name;
373 $customGroups[$dao->id]['title'] = $dao->title;
374 $customGroups[$dao->id]['extends'] = $dao->extends_entity_column_value;
375 }
376 }
377
378 return $customGroups;
379 }
380
381 /**
100fef9d 382 * Update the is_active flag in the db
6a488035 383 *
7aaf6db0
TO
384 * @param int $id
385 * Id of the database record.
386 * @param bool $is_active
387 * Value we want to set the is_active field.
6a488035 388 *
a6c01b45
CW
389 * @return Object
390 * DAO object on sucess, null otherwise
6a488035
TO
391 * @static
392 */
00be9182 393 public static function setIsActive($id, $is_active) {
6a488035
TO
394 return CRM_Core_DAO::setFieldValue('CRM_Campaign_DAO_Survey', $id, 'is_active', $is_active);
395 }
396
397 /**
100fef9d 398 * Delete the survey
6a488035 399 *
7aaf6db0
TO
400 * @param int $id
401 * Survey id.
6a488035 402 *
77b97be7 403 * @return mixed|null
6a488035 404 * @static
6a488035 405 */
00be9182 406 public static function del($id) {
6a488035
TO
407 if (!$id) {
408 return NULL;
409 }
410 $reportId = CRM_Campaign_BAO_Survey::getReportID($id);
9b873358 411 if ($reportId) {
0b25329b 412 CRM_Report_BAO_ReportInstance::del($reportId);
6a488035
TO
413 }
414 $dao = new CRM_Campaign_DAO_Survey();
415 $dao->id = $id;
416 return $dao->delete();
417 }
418
419 /**
420 * This function retrieve contact information.
421 *
c490a46a 422 * @param array $voterIds
7aaf6db0
TO
423 * @param array $returnProperties
424 * An array of return elements.
6a488035 425 *
a6c01b45
CW
426 * @return array
427 * array of contact info.
c490a46a 428 * @static
6a488035 429 */
00be9182 430 public static function voterDetails($voterIds, $returnProperties = array()) {
6a488035
TO
431 $voterDetails = array();
432 if (!is_array($voterIds) || empty($voterIds)) {
433 return $voterDetails;
434 }
435
436 if (empty($returnProperties)) {
437 $autocompleteContactSearch = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
438 'contact_autocomplete_options'
439 );
440 $returnProperties = array_fill_keys(array_merge(array(
441 'contact_type',
442 'contact_sub_type',
443 'sort_name',
444 ),
445 array_keys($autocompleteContactSearch)
446 ), 1);
447 }
448
449 $select = $from = array();
450 foreach ($returnProperties as $property => $ignore) {
451 $value = (in_array($property, array(
452 'city', 'street_address'))) ? 'address' : $property;
453 switch ($property) {
454 case 'sort_name':
455 case 'contact_type':
456 case 'contact_sub_type':
457 $select[] = "$property as $property";
458 $from['contact'] = 'civicrm_contact contact';
459 break;
460
461 case 'email':
462 case 'phone':
463 case 'city':
464 case 'street_address':
465 $select[] = "$property as $property";
466 $from[$value] = "LEFT JOIN civicrm_{$value} {$value} ON ( contact.id = {$value}.contact_id AND {$value}.is_primary = 1 ) ";
467 break;
468
469 case 'country':
470 case 'state_province':
471 $select[] = "{$property}.name as $property";
472 if (!in_array('address', $from)) {
473 $from['address'] = 'LEFT JOIN civicrm_address address ON ( contact.id = address.contact_id AND address.is_primary = 1) ';
474 }
475 $from[$value] = " LEFT JOIN civicrm_{$value} {$value} ON ( address.{$value}_id = {$value}.id ) ";
476 break;
477 }
478 }
479
480 //finally retrieve contact details.
481 if (!empty($select) && !empty($from)) {
482 $fromClause = implode(' ', $from);
483 $selectClause = implode(', ', $select);
484 $whereClause = "contact.id IN (" . implode(',', $voterIds) . ')';
485
486 $query = "
91da6cd5 487 SELECT contact.id as contactId, $selectClause
6a488035
TO
488 FROM $fromClause
489 WHERE $whereClause
490Group By contact.id";
491
492 $contact = CRM_Core_DAO::executeQuery($query);
493 while ($contact->fetch()) {
494 $voterDetails[$contact->contactId]['contact_id'] = $contact->contactId;
495 foreach ($returnProperties as $property => $ignore) {
496 $voterDetails[$contact->contactId][$property] = $contact->$property;
497 }
5c2ea586 498 $image = CRM_Contact_BAO_Contact_Utils::getImage($contact->contact_sub_type ? $contact->contact_sub_type : $contact->contact_type,
6a488035
TO
499 FALSE,
500 $contact->contactId
501 );
502 $voterDetails[$contact->contactId]['contact_type'] = $image;
503 }
504 $contact->free();
505 }
506
507 return $voterDetails;
508 }
509
510 /**
511 * This function retrieve survey related activities w/ for give voter ids.
512 *
7aaf6db0
TO
513 * @param int $surveyId
514 * Survey id.
515 * @param array $voterIds
516 * VoterIds.
6a488035 517 *
100fef9d 518 * @param int $interviewerId
2a6da8d7
EM
519 * @param array $statusIds
520 *
a6c01b45
CW
521 * @return array
522 * array of survey activity.
e0b82b44 523 * @static
6a488035 524 */
5c2ea586
TO
525 static function voterActivityDetails(
526 $surveyId, $voterIds, $interviewerId = NULL,
6a488035
TO
527 $statusIds = array()) {
528 $activityDetails = array();
529 if (!$surveyId ||
530 !is_array($voterIds) || empty($voterIds)
531 ) {
532 return $activityDetails;
533 }
534
535 $whereClause = NULL;
536 if (is_array($statusIds) && !empty($statusIds)) {
537 $whereClause = ' AND ( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
538 }
539
6a488035 540 $targetContactIds = ' ( ' . implode(',', $voterIds) . ' ) ';
e7e657f0 541 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
9e74e3ce 542 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
543 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
8ef12e64 544
64e716d7 545 $params[1] = array($surveyId, 'Integer');
91da6cd5
DL
546 $query = "
547 SELECT activity.id, activity.status_id,
baf8a079 548 activityTarget.contact_id as voter_id,
549 activityAssignment.contact_id as interviewer_id
6a488035 550 FROM civicrm_activity activity
91da6cd5 551INNER JOIN civicrm_activity_contact activityTarget
9e74e3ce 552 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
91da6cd5 553INNER JOIN civicrm_activity_contact activityAssignment
9e74e3ce 554 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
6a488035 555 WHERE activity.source_record_id = %1
64e716d7 556 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 ) ";
22e263ad 557 if (!empty($interviewerId)) {
64e716d7
JM
558 $query .= "AND activityAssignment.contact_id = %2 ";
559 $params[2] = array($interviewerId, 'Integer');
560 }
561 $query .= "AND activityTarget.contact_id IN {$targetContactIds}
6a488035 562 $whereClause";
77b97be7 563 $activity = CRM_Core_DAO::executeQuery($query, $params);
6a488035
TO
564 while ($activity->fetch()) {
565 $activityDetails[$activity->voter_id] = array(
566 'voter_id' => $activity->voter_id,
567 'status_id' => $activity->status_id,
568 'activity_id' => $activity->id,
569 'interviewer_id' => $activity->interviewer_id,
570 );
571 }
572
573 return $activityDetails;
574 }
575
576 /**
577 * This function retrieve survey related activities.
578 *
7aaf6db0 579 * @param int $surveyId
100fef9d 580 * @param int $interviewerId
f220017a
CW
581 * @param array $statusIds
582 * @param array $voterIds
2a6da8d7 583 * @param bool $onlyCount
f220017a
CW
584 *
585 * @return array
586 * An array of survey activity.
e0b82b44 587 * @static
6a488035 588 */
5c2ea586
TO
589 static function getSurveyActivities(
590 $surveyId,
6a488035 591 $interviewerId = NULL,
5c2ea586
TO
592 $statusIds = NULL,
593 $voterIds = NULL,
594 $onlyCount = FALSE
6a488035
TO
595 ) {
596 $activities = array();
597 $surveyActivityCount = 0;
598 if (!$surveyId) {
599 return ($onlyCount) ? 0 : $activities;
600 }
601
602 $where = array();
603 if (!empty($statusIds)) {
604 $where[] = '( activity.status_id IN ( ' . implode(',', array_values($statusIds)) . ' ) )';
605 }
606
607 if ($interviewerId) {
5161d8be 608 $where[] = "( activityAssignment.contact_id = $interviewerId )";
6a488035
TO
609 }
610
611 if (!empty($voterIds)) {
5161d8be 612 $where[] = "( activityTarget.contact_id IN ( " . implode(',', $voterIds) . " ) )";
6a488035
TO
613 }
614
615 $whereClause = NULL;
616 if (!empty($where)) {
617 $whereClause = ' AND ( ' . implode(' AND ', $where) . ' )';
618 }
619
620 $actTypeId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
621 if (!$actTypeId) {
622 return $activities;
623 }
624
625 if ($onlyCount) {
626 $select = "SELECT count(activity.id)";
627 }
628 else {
629 $select = "
91da6cd5 630 SELECT activity.id, activity.status_id,
5161d8be 631 activityTarget.contact_id as voter_id,
632 activityAssignment.contact_id as interviewer_id,
6a488035
TO
633 activity.result as result,
634 activity.activity_date_time as activity_date_time,
635 contact_a.display_name as voter_name";
636 }
637
e7e657f0 638 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
9e74e3ce 639 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
640 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
641
6a488035
TO
642 $query = "
643 $select
644 FROM civicrm_activity activity
91da6cd5 645INNER JOIN civicrm_activity_contact activityTarget
9e74e3ce 646 ON ( activityTarget.activity_id = activity.id AND activityTarget.record_type_id = $targetID )
91da6cd5 647INNER JOIN civicrm_activity_contact activityAssignment
9e74e3ce 648 ON ( activityAssignment.activity_id = activity.id AND activityAssignment.record_type_id = $assigneeID )
91da6cd5 649INNER JOIN civicrm_contact contact_a ON ( activityTarget.contact_id = contact_a.id )
6a488035
TO
650 WHERE activity.source_record_id = %1
651 AND activity.activity_type_id = %2
652 AND ( activity.is_deleted IS NULL OR activity.is_deleted = 0 )
653 $whereClause";
654
5c2ea586
TO
655 $params = array(
656 1 => array($surveyId, 'Integer'),
6a488035
TO
657 2 => array($actTypeId, 'Integer'),
658 );
659
660 if ($onlyCount) {
661 $dbCount = CRM_Core_DAO::singleValueQuery($query, $params);
662 return ($dbCount) ? $dbCount : 0;
663 }
664
665 $activity = CRM_Core_DAO::executeQuery($query, $params);
666
667 while ($activity->fetch()) {
668 $activities[$activity->id] = array(
669 'id' => $activity->id,
670 'voter_id' => $activity->voter_id,
671 'voter_name' => $activity->voter_name,
672 'status_id' => $activity->status_id,
673 'interviewer_id' => $activity->interviewer_id,
674 'result' => $activity->result,
21dfd5f5 675 'activity_date_time' => $activity->activity_date_time,
6a488035
TO
676 );
677 }
678
679 return $activities;
680 }
681
682 /**
dc195289 683 * Retrieve survey voter information.
6a488035 684 *
7aaf6db0
TO
685 * @param int $surveyId
686 * Survey id.
687 * @param int $interviewerId
688 * Interviewer id.
689 * @param array $statusIds
690 * Survey status ids.
6a488035 691 *
dc195289
CW
692 * @return array
693 * Survey related contact ids.
6a488035
TO
694 * @static
695 */
5c2ea586 696 public static function getSurveyVoterInfo($surveyId, $interviewerId = NULL, $statusIds = array()) {
6a488035
TO
697 $voterIds = array();
698 if (!$surveyId) {
699 return $voterIds;
700 }
701
702 $cacheKey = $surveyId;
703 if ($interviewerId) {
704 $cacheKey .= "_{$interviewerId}";
705 }
706 if (is_array($statusIds) && !empty($statusIds)) {
707 $cacheKey = "{$cacheKey}_" . implode('_', $statusIds);
708 }
709
710 static $contactIds = array();
711 if (!isset($contactIds[$cacheKey])) {
712 $activities = self::getSurveyActivities($surveyId, $interviewerId, $statusIds);
713 foreach ($activities as $values) {
714 $voterIds[$values['voter_id']] = $values;
715 }
716 $contactIds[$cacheKey] = $voterIds;
717 }
718
719 return $contactIds[$cacheKey];
720 }
721
722 /**
91da6cd5 723 * This function retrieve all option groups which are created as a result set
6a488035 724 *
2a6da8d7 725 * @param string $valueColumnName
a6c01b45
CW
726 * @return array
727 * an array of option groups.
e0b82b44 728 * @static
6a488035 729 */
5c2ea586 730 public static function getResultSets($valueColumnName = 'title') {
6a488035
TO
731 $resultSets = array();
732 $valueColumnName = CRM_Utils_Type::escape($valueColumnName, 'String');
733
734 $query = "SELECT id, {$valueColumnName} FROM civicrm_option_group WHERE name LIKE 'civicrm_survey_%' AND is_active=1";
735 $dao = CRM_Core_DAO::executeQuery($query);
736 while ($dao->fetch()) {
737 $resultSets[$dao->id] = $dao->$valueColumnName;
738 }
739
740 return $resultSets;
741 }
742
743 /**
dc195289 744 * check survey activity.
6a488035 745 *
7aaf6db0
TO
746 * @param int $activityId
747 * Activity id.
a6c01b45 748 * @return boolean
6a488035
TO
749 * @static
750 */
00be9182 751 public static function isSurveyActivity($activityId) {
6a488035
TO
752 $isSurveyActivity = FALSE;
753 if (!$activityId) {
754 return $isSurveyActivity;
755 }
756
757 $activity = new CRM_Activity_DAO_Activity();
758 $activity->id = $activityId;
759 $activity->selectAdd('source_record_id, activity_type_id');
760 if ($activity->find(TRUE) &&
761 $activity->source_record_id
762 ) {
763 $surveyActTypes = self::getSurveyActivityType();
764 if (array_key_exists($activity->activity_type_id, $surveyActTypes)) {
765 $isSurveyActivity = TRUE;
766 }
767 }
768
769 return $isSurveyActivity;
770 }
771
772 /**
773 * This function retrive all response options of survey
774 *
7aaf6db0
TO
775 * @param int $surveyId
776 * Survey id.
a6c01b45
CW
777 * @return array
778 * an array of option values
e0b82b44 779 * @static
6a488035 780 */
00be9182 781 public static function getResponsesOptions($surveyId) {
6a488035
TO
782 $responseOptions = array();
783 if (!$surveyId) {
784 return $responseOptions;
785 }
786
787 $resultId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'result_id');
788 if ($resultId) {
789 $responseOptions = CRM_Core_OptionGroup::valuesByID($resultId);
790 }
791
792 return $responseOptions;
793 }
794
795 /**
796 * This function return all voter links with respecting permissions
797 *
100fef9d 798 * @param int $surveyId
2a6da8d7
EM
799 * @param bool $enclosedInUL
800 * @param string $extraULName
e0b82b44
CW
801 * @return array|string $url array of permissioned links
802 * @static
6a488035 803 */
00be9182 804 public static function buildPermissionLinks($surveyId, $enclosedInUL = FALSE, $extraULName = 'more') {
6a488035
TO
805 $menuLinks = array();
806 if (!$surveyId) {
807 return $menuLinks;
808 }
809
810 static $voterLinks = array();
811 if (empty($voterLinks)) {
812 $permissioned = FALSE;
813 if (CRM_Core_Permission::check('manage campaign') ||
814 CRM_Core_Permission::check('administer CiviCampaign')
815 ) {
816 $permissioned = TRUE;
817 }
818
819 if ($permissioned || CRM_Core_Permission::check("reserve campaign contacts")) {
820 $voterLinks['reserve'] = array(
821 'name' => 'reserve',
822 'url' => 'civicrm/survey/search',
2db64250 823 'qs' => 'sid=%%id%%&reset=1&op=reserve',
6a488035
TO
824 'title' => ts('Reserve Respondents'),
825 );
826 }
827 if ($permissioned || CRM_Core_Permission::check("interview campaign contacts")) {
828 $voterLinks['release'] = array(
829 'name' => 'interview',
830 'url' => 'civicrm/survey/search',
831 'qs' => 'sid=%%id%%&reset=1&op=interview&force=1',
832 'title' => ts('Interview Respondents'),
833 );
834 }
835 if ($permissioned || CRM_Core_Permission::check("release campaign contacts")) {
836 $voterLinks['interview'] = array(
837 'name' => 'release',
838 'url' => 'civicrm/survey/search',
839 'qs' => 'sid=%%id%%&reset=1&op=release&force=1',
840 'title' => ts('Release Respondents'),
841 );
842 }
843 }
844
845 if (CRM_Core_Permission::check('access CiviReport')) {
846 $reportID = self::getReportID($surveyId);
847 if ($reportID) {
91da6cd5 848 $voterLinks['report'] =
6a488035
TO
849 array(
850 'name' => 'report',
851 'url' => "civicrm/report/instance/{$reportID}",
852 'qs' => 'reset=1',
853 'title' => ts('View Survey Report'),
854 );
855 }
856 }
857
858 $ids = array('id' => $surveyId);
859 foreach ($voterLinks as $link) {
a7488080 860 if (!empty($link['qs']) &&
6a488035
TO
861 !CRM_Utils_System::isNull($link['qs'])
862 ) {
863 $urlPath = CRM_Utils_System::url(CRM_Core_Action::replace($link['url'], $ids),
864 CRM_Core_Action::replace($link['qs'], $ids)
865 );
a1c7d42f 866 $menuLinks[] = sprintf('<a href="%s" class="action-item crm-hover-button" title="%s">%s</a>',
6a488035
TO
867 $urlPath,
868 CRM_Utils_Array::value('title', $link),
869 $link['title']
870 );
871 }
872 }
873 if ($enclosedInUL) {
874 $extraLinksName = strtolower($extraULName);
875 $allLinks = '';
876 CRM_Utils_String::append($allLinks, '</li><li>', $menuLinks);
877 $allLinks = "$extraULName <ul id='panel_{$extraLinksName}_xx' class='panel'><li>{$allLinks}</li></ul>";
a1c7d42f 878 $menuLinks = "<span class='btn-slide crm-hover-button' id={$extraLinksName}_xx>{$allLinks}</span>";
6a488035
TO
879 }
880
881 return $menuLinks;
882 }
883
884 /**
100fef9d 885 * Retrieve survey associated profile id.
6a488035
TO
886 */
887 public static function getSurveyProfileId($surveyId) {
888 if (!$surveyId) {
889 return NULL;
890 }
891
892 static $ufIds = array();
893 if (!array_key_exists($surveyId, $ufIds)) {
894 //get the profile id.
895 $ufJoinParams = array(
896 'entity_id' => $surveyId,
897 'entity_table' => 'civicrm_survey',
898 'module' => 'CiviCampaign',
899 );
91da6cd5 900
6a488035
TO
901 list($first, $second) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
902
903 if ($first) {
91da6cd5 904 $ufIds[$surveyId] = array($first);
6a488035
TO
905 }
906 if ($second) {
91da6cd5 907 $ufIds[$surveyId][] = array_shift($second);
6a488035
TO
908 }
909 }
910
47dd4836 911 return CRM_Utils_Array::value($surveyId, $ufIds);
6a488035
TO
912 }
913
30c4e065 914 /**
100fef9d 915 * @param int $surveyId
30c4e065
EM
916 *
917 * @return mixed
918 */
6a488035
TO
919 public Static function getReportID($surveyId) {
920 static $reportIds = array();
921
922 if (!array_key_exists($surveyId, $reportIds)) {
923 $query = "SELECT MAX(id) as id FROM civicrm_report_instance WHERE name = %1";
5c2ea586 924 $reportID = CRM_Core_DAO::singleValueQuery($query, array(1 => array("survey_{$surveyId}", 'String')));
6a488035
TO
925 $reportIds[$surveyId] = $reportID;
926 }
927 return $reportIds[$surveyId];
928 }
929
930 /**
100fef9d 931 * Decides the contact type for given survey.
6a488035
TO
932 */
933 public static function getSurveyContactType($surveyId) {
934 $contactType = NULL;
935
936 //apply filter of profile type on search.
937 $profileId = self::getSurveyProfileId($surveyId);
938 if ($profileId) {
939 $profileType = CRM_Core_BAO_UFField::getProfileType($profileId);
940 if (in_array($profileType, CRM_Contact_BAO_ContactType::basicTypes())) {
941 $contactType = $profileType;
942 }
943 }
944
945 return $contactType;
946 }
947
948 /**
100fef9d 949 * Get survey supportable profile types
6a488035
TO
950 */
951 public static function surveyProfileTypes() {
952 static $profileTypes;
953
954 if (!isset($profileTypes)) {
955 $profileTypes = array_merge(array('Activity', 'Contact'), CRM_Contact_BAO_ContactType::basicTypes());
5c2ea586 956 $profileTypes = array_diff($profileTypes, array('Organization', 'Household'));
6a488035
TO
957 }
958
959 return $profileTypes;
960 }
961
962 /**
963 * Get the valid survey response fields those
964 * are configured with profile and custom fields.
965 *
7aaf6db0
TO
966 * @param int $surveyId
967 * Survey id.
968 * @param int $surveyTypeId
969 * Survey activity type id.
6a488035 970 *
a6c01b45
CW
971 * @return array
972 * an array of valid survey response fields.
6a488035
TO
973 */
974 public static function getSurveyResponseFields($surveyId, $surveyTypeId = NULL) {
975 if (empty($surveyId)) {
976 return array();
977 }
978
979 static $responseFields;
980 $cacheKey = "{$surveyId}_{$surveyTypeId}";
981
982 if (isset($responseFields[$cacheKey])) {
983 return $responseFields[$cacheKey];
984 }
985
986 $responseFields[$cacheKey] = array();
987
988 $profileId = self::getSurveyProfileId($surveyId);
989
990 if (!$profileId) {
991 return $responseFields;
992 }
993
994 if (!$surveyTypeId) {
995 $surveyTypeId = CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Survey', $surveyId, 'activity_type_id');
996 }
997
998 $profileFields = CRM_Core_BAO_UFGroup::getFields($profileId,
5e5141ea 999 FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, 'field_name', TRUE
6a488035
TO
1000 );
1001
1002 //don't load these fields in grid.
1003 $removeFields = array('File', 'RichTextEditor');
1004
1005 $supportableFieldTypes = self::surveyProfileTypes();
1006
1007 // get custom fields of type survey
1008 $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $surveyTypeId);
1009
1010 foreach ($profileFields as $name => $field) {
1011 //get only contact and activity fields.
1012 //later stage we might going to consider contact type also.
4e9ab75a
RN
1013 if (in_array($field['field_type'], $supportableFieldTypes)) {
1014 // we should allow all supported custom data for survey
1015 // In case of activity, allow normal activity and with subtype survey,
1016 // suppress custom data of other activity types
1017 if (CRM_Core_BAO_CustomField::getKeyID($name)) {
1018 if (!in_array($field['html_type'], $removeFields)) {
1019 if ($field['field_type'] != 'Activity') {
1020 $responseFields[$cacheKey][$name] = $field;
1021 }
1022 elseif (array_key_exists(CRM_Core_BAO_CustomField::getKeyID($name), $customFields)) {
1023 $responseFields[$cacheKey][$name] = $field;
1024 }
1025 }
6a488035 1026 }
4e9ab75a 1027 else {
6a488035
TO
1028 $responseFields[$cacheKey][$name] = $field;
1029 }
1030 }
6a488035
TO
1031 }
1032
1033 return $responseFields[$cacheKey];
1034 }
1035
1036 /**
1037 * Get all interviewers of surveys.
1038 *
a6c01b45
CW
1039 * @return array
1040 * an array of valid survey response fields.
6a488035
TO
1041 */
1042 public static function getInterviewers() {
1043 static $interviewers;
1044
1045 if (isset($interviewers)) {
1046 return $interviewers;
1047 }
1048
1049 $whereClause = NULL;
1050 $activityTypes = self::getSurveyActivityType();
1051 if (!empty($activityTypes)) {
1052 $whereClause = ' WHERE survey.activity_type_id IN ( ' . implode(' , ', array_keys($activityTypes)) . ' )';
1053 }
1054
1055 $interviewers = array();
e7e657f0 1056 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
9e74e3ce 1057 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
6a488035
TO
1058
1059 $query = "
91da6cd5 1060 SELECT contact.id as id,
6a488035 1061 contact.sort_name as sort_name
91da6cd5 1062 FROM civicrm_contact contact
9e74e3ce 1063INNER JOIN civicrm_activity_contact assignment ON ( assignment.contact_id = contact.id AND record_type_id = $assigneeID )
6a488035
TO
1064INNER JOIN civicrm_activity activity ON ( activity.id = assignment.activity_id )
1065INNER JOIN civicrm_survey survey ON ( activity.source_record_id = survey.id )
1066 {$whereClause}";
1067
1068 $interviewer = CRM_Core_DAO::executeQuery($query);
1069 while ($interviewer->fetch()) {
1070 $interviewers[$interviewer->id] = $interviewer->sort_name;
1071 }
1072
1073 return $interviewers;
1074 }
1075
1076 /**
1077 * Check and update the survey respondents.
1078 *
c490a46a 1079 * @param array $params
dd244018 1080 *
a6c01b45
CW
1081 * @return array
1082 * success message
6a488035 1083 */
7b60d5b9 1084 public static function releaseRespondent($params) {
6a488035
TO
1085 $activityStatus = CRM_Core_PseudoConstant::activityStatus('name');
1086 $reserveStatusId = array_search('Scheduled', $activityStatus);
1087 $surveyActivityTypes = CRM_Campaign_BAO_Survey::getSurveyActivityType();
7b60d5b9 1088 if (!empty($surveyActivityTypes) && is_array($surveyActivityTypes)) {
1089 $surveyActivityTypesIds = array_keys($surveyActivityTypes);
1090 }
6a488035
TO
1091
1092 //retrieve all survey activities related to reserve action.
1093 $releasedCount = 0;
1094 if ($reserveStatusId && !empty($surveyActivityTypesIds)) {
1095 $query = '
91da6cd5 1096 SELECT activity.id as id,
6a488035
TO
1097 activity.activity_date_time as activity_date_time,
1098 survey.id as surveyId,
1099 survey.release_frequency as release_frequency
1100 FROM civicrm_activity activity
91da6cd5
DL
1101INNER JOIN civicrm_survey survey ON ( survey.id = activity.source_record_id )
1102 WHERE activity.is_deleted = 0
1103 AND activity.status_id = %1
6a488035
TO
1104 AND activity.activity_type_id IN ( ' . implode(', ', $surveyActivityTypesIds) . ' )';
1105 $activity = CRM_Core_DAO::executeQuery($query, array(1 => array($reserveStatusId, 'Positive')));
1106 $releasedIds = array();
1107 while ($activity->fetch()) {
1108 if (!$activity->release_frequency) {
1109 continue;
1110 }
1111 $reservedSeconds = CRM_Utils_Date::unixTime($activity->activity_date_time);
1112 $releasedSeconds = $activity->release_frequency * 24 * 3600;
1113 $totalReservedSeconds = $reservedSeconds + $releasedSeconds;
1114 if ($totalReservedSeconds < time()) {
1115 $releasedIds[$activity->id] = $activity->id;
1116 }
1117 }
1118
1119 //released respondent.
1120 if (!empty($releasedIds)) {
1121 $query = '
1122UPDATE civicrm_activity
1123 SET is_deleted = 1
1124 WHERE id IN ( ' . implode(', ', $releasedIds) . ' )';
1125 CRM_Core_DAO::executeQuery($query);
1126 $releasedCount = count($releasedIds);
1127 }
1128 }
1129
1130 $rtnMsg = array(
1131 'is_error' => 0,
1132 'messages' => "Number of respondents released = {$releasedCount}",
1133 );
1134
1135 return $rtnMsg;
1136 }
a2015e41
CW
1137
1138 /**
1139 * Get options for a given field.
1140 * @see CRM_Core_DAO::buildOptions
1141 *
7aaf6db0
TO
1142 * @param string $fieldName
1143 * @param string $context: @see CRM_Core_DAO::buildOptionsContext
1144 * @param array $props: whatever is known about this dao object
a2015e41
CW
1145 *
1146 * @return array|bool
1147 */
1148 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1149 $params = array();
1150 // Special logic for fields whose options depend on context or properties
1151 switch ($fieldName) {
1152 case 'activity_type_id':
1153 $campaignCompId = CRM_Core_Component::getComponentID('CiviCampaign');
1154 if ($campaignCompId) {
1155 $params['condition'] = array("component_id={$campaignCompId}", "v.name != 'Petition'");
1156 }
1157 break;
1158 }
1159 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
1160 }
6a488035 1161}