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