ILIAS  release_5-1 Revision 5.0.0-5477-g43f3e3fab5
class.ilObjSurvey.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (c) 1998-2010 ILIAS open source, Extended GPL, see docs/LICENSE */
3 
4 include_once "./Services/Object/classes/class.ilObject.php";
5 
15 class ilObjSurvey extends ilObject
16 {
17  const STATUS_OFFLINE = 0;
18  const STATUS_ONLINE = 1;
19 
23 
24  const INVITATION_OFF = 0;
25  const INVITATION_ON = 1;
26 
27  const MODE_UNLIMITED = 0;
29 
30  const ANONYMIZE_OFF = 0; // personalized, no codes
31  const ANONYMIZE_ON = 1; // anonymized, codes
32  const ANONYMIZE_FREEACCESS = 2; // anonymized, no codes
33  const ANONYMIZE_CODE_ALL = 3; // personalized, codes
34 
37 
45 
52  var $author;
53 
60 
66  var $outro;
67 
73  var $status;
74 
81 
88 
94  var $end_date;
95 
102 
109 
116 
122 
128 
135 
141 
145 
146  // 360°
147  protected $mode_360; // [bool]
148  protected $mode_360_self_eval; // [bool]
149  protected $mode_360_self_appr; // [bool]
150  protected $mode_360_self_rate; // [bool]
151  protected $mode_360_results; // [int]
152  protected $mode_360_skill_service; // [bool]
153 
154  const RESULTS_360_NONE = 0;
155  const RESULTS_360_OWN = 1;
156  const RESULTS_360_ALL = 2;
157 
158  // reminder/notification
159  protected $reminder_status; // [bool]
160  protected $reminder_start; // [ilDate]
161  protected $reminder_end; // [ilDate]
162  protected $reminder_frequency; // [int]
163  protected $reminder_target; // [int]
164  protected $reminder_last_sent; // [bool]
165  protected $tutor_ntf_status; // [bool]
166  protected $tutor_ntf_recipients; // [array]
167  protected $tutor_ntf_target; // [int]
168 
169  protected $view_own_results; // [bool]
170  protected $mail_own_results; // [bool]
171 
174 
175 
182  function ilObjSurvey($a_id = 0,$a_call_by_reference = true)
183  {
184  global $ilUser, $lng;
185 
186  $this->type = "svy";
187  $this->survey_id = -1;
188  $this->introduction = "";
189  $this->outro = $lng->txt("survey_finished");
190  $this->author = $ilUser->getFullname();
191  $this->status = self::STATUS_OFFLINE;
192  $this->evaluation_access = self::EVALUATION_ACCESS_OFF;
193  $this->questions = array();
194  $this->invitation = self::INVITATION_OFF;
195  $this->invitation_mode = self::MODE_PREDEFINED_USERS;
196  $this->anonymize = self::ANONYMIZE_OFF;
197  $this->display_question_titles = self::QUESTIONTITLES_VISIBLE;
198  $this->surveyCodeSecurity = TRUE;
199  $this->template_id = NULL;
200  $this->pool_usage = true;
201 
202  parent::__construct($a_id,$a_call_by_reference);
203  }
204 
208  function create($a_upload = false)
209  {
210  parent::create();
211  if(!$a_upload)
212  {
213  $this->createMetaData();
214  }
215  }
216 
222  function createMetaData()
223  {
224  parent::createMetaData();
225  $this->saveAuthorToMetadata();
226  }
227 
234  function update()
235  {
236  $this->updateMetaData();
237 
238  if (!parent::update())
239  {
240  return false;
241  }
242 
243  // put here object specific stuff
244 
245  return true;
246  }
247 
248  function createReference()
249  {
250  $result = parent::createReference();
251  $this->saveToDb();
252  return $result;
253  }
254 
260  function read($a_force_db = false)
261  {
262  parent::read($a_force_db);
263  $this->loadFromDb();
264  }
265 
272  function addQuestion($question_id)
273  {
274  array_push($this->questions, $question_id);
275  }
276 
277 
284  function delete()
285  {
286  if ($this->countReferences() == 1)
287  {
288  $this->deleteMetaData();
289 
290  // Delete all survey questions, constraints and materials
291  foreach ($this->questions as $question_id)
292  {
293  $this->removeQuestion($question_id);
294  }
295  $this->deleteSurveyRecord();
296 
298  }
299 
300  $remove = parent::delete();
301 
302  // always call parent delete function first!!
303  if (!$remove)
304  {
305  return false;
306  }
307  return true;
308  }
309 
316  {
317  global $ilDB;
318 
319  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_svy WHERE survey_id = %s",
320  array('integer'),
321  array($this->getSurveyId())
322  );
323 
324  $result = $ilDB->queryF("SELECT questionblock_fi FROM svy_qblk_qst WHERE survey_fi = %s",
325  array('integer'),
326  array($this->getSurveyId())
327  );
328  $questionblocks = array();
329  while ($row = $ilDB->fetchAssoc($result))
330  {
331  array_push($questionblocks, $row["questionblock_fi"]);
332  }
333  if (count($questionblocks))
334  {
335  $affectedRows = $ilDB->manipulate("DELETE FROM svy_qblk WHERE " . $ilDB->in('questionblock_id', $questionblocks, false, 'integer'));
336  }
337  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE survey_fi = %s",
338  array('integer'),
339  array($this->getSurveyId())
340  );
341  $this->deleteAllUserData();
342 
343  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_anonymous WHERE survey_fi = %s",
344  array('integer'),
345  array($this->getSurveyId())
346  );
347 
348  // delete export files
349  include_once "./Services/Utilities/classes/class.ilUtil.php";
350  $svy_data_dir = ilUtil::getDataDir()."/svy_data";
351  $directory = $svy_data_dir."/svy_".$this->getId();
352  if (is_dir($directory))
353  {
354  include_once "./Services/Utilities/classes/class.ilUtil.php";
355  ilUtil::delDir($directory);
356  }
357 
358  include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php");
359  $mobs = ilObjMediaObject::_getMobsOfObject("svy:html", $this->getId());
360  // remaining usages are not in text anymore -> delete them
361  // and media objects (note: delete method of ilObjMediaObject
362  // checks whether object is used in another context; if yes,
363  // the object is not deleted!)
364  foreach($mobs as $mob)
365  {
366  ilObjMediaObject::_removeUsage($mob, "svy:html", $this->getId());
367  $mob_obj =& new ilObjMediaObject($mob);
368  $mob_obj->delete();
369  }
370  }
371 
377  function deleteAllUserData()
378  {
379  global $ilDB;
380 
381  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
382  array('integer'),
383  array($this->getSurveyId())
384  );
385  $active_array = array();
386  while ($row = $ilDB->fetchAssoc($result))
387  {
388  array_push($active_array, $row["finished_id"]);
389  }
390 
391  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_finished WHERE survey_fi = %s",
392  array('integer'),
393  array($this->getSurveyId())
394  );
395 
396  foreach ($active_array as $active_fi)
397  {
398  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE active_fi = %s",
399  array('integer'),
400  array($active_fi)
401  );
402  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_times WHERE finished_fi = %s",
403  array('integer'),
404  array($active_fi)
405  );
406  }
407 
408  include_once "Services/Object/classes/class.ilObjectLP.php";
409  $lp_obj = ilObjectLP::getInstance($this->getId());
410  $lp_obj->resetLPDataForCompleteObject();
411  }
412 
418  function removeSelectedSurveyResults($finished_ids)
419  {
420  global $ilDB;
421 
422  $user_ids[] = array();
423 
424  foreach ($finished_ids as $finished_id)
425  {
426  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE finished_id = %s",
427  array('integer'),
428  array($finished_id)
429  );
430  $row = $ilDB->fetchAssoc($result);
431 
432  if($row["user_fi"])
433  {
434  $user_ids[] = $row["user_fi"];
435  }
436 
437  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE active_fi = %s",
438  array('integer'),
439  array($row["finished_id"])
440  );
441 
442  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_finished WHERE finished_id = %s",
443  array('integer'),
444  array($finished_id)
445  );
446 
447  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_times WHERE finished_fi = %s",
448  array('integer'),
449  array($row["finished_id"])
450  );
451  }
452 
453  if(sizeof($user_ids))
454  {
455  include_once "Services/Object/classes/class.ilObjectLP.php";
456  $lp_obj = ilObjectLP::getInstance($this->getId());
457  $lp_obj->resetLPDataForUserIds($user_ids);
458  }
459  }
460 
461  function &getSurveyParticipants($finished_ids = null)
462  {
463  global $ilDB;
464 
465  $sql = "SELECT * FROM svy_finished".
466  " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer");
467  if($finished_ids)
468  {
469  $sql .= " AND ".$ilDB->in("finished_id", $finished_ids, "", "integer");
470  }
471 
472  $result = $ilDB->query($sql);
473  $participants = array();
474  if ($result->numRows() > 0)
475  {
476  while ($row = $ilDB->fetchAssoc($result))
477  {
478  $userdata = $this->getUserDataFromActiveId($row["finished_id"]);
479  $userdata["finished"] = (bool)$row["state"];
480  $userdata["finished_tstamp"] = $row["tstamp"];
481  $participants[$userdata["sortname"] . $userdata["active_id"]] = $userdata;
482  }
483  }
484  return $participants;
485  }
486 
500  function notify($a_event,$a_ref_id,$a_parent_non_rbac_id,$a_node_id,$a_params = 0)
501  {
502  global $tree;
503 
504  switch ($a_event)
505  {
506  case "link":
507 
508  //var_dump("<pre>",$a_params,"</pre>");
509  //echo "Module name ".$this->getRefId()." triggered by link event. Objects linked into target object ref_id: ".$a_ref_id;
510  //exit;
511  break;
512 
513  case "cut":
514 
515  //echo "Module name ".$this->getRefId()." triggered by cut event. Objects are removed from target object ref_id: ".$a_ref_id;
516  //exit;
517  break;
518 
519  case "copy":
520 
521  //var_dump("<pre>",$a_params,"</pre>");
522  //echo "Module name ".$this->getRefId()." triggered by copy event. Objects are copied into target object ref_id: ".$a_ref_id;
523  //exit;
524  break;
525 
526  case "paste":
527 
528  //echo "Module name ".$this->getRefId()." triggered by paste (cut) event. Objects are pasted into target object ref_id: ".$a_ref_id;
529  //exit;
530  break;
531 
532  case "new":
533 
534  //echo "Module name ".$this->getRefId()." triggered by paste (new) event. Objects are applied to target object ref_id: ".$a_ref_id;
535  //exit;
536  break;
537  }
538 
539  // At the beginning of the recursive process it avoids second call of the notify function with the same parameter
540  if ($a_node_id==$_GET["ref_id"])
541  {
542  $parent_obj =& $this->ilias->obj_factory->getInstanceByRefId($a_node_id);
543  $parent_type = $parent_obj->getType();
544  if($parent_type == $this->getType())
545  {
546  $a_node_id = (int) $tree->getParentId($a_node_id);
547  }
548  }
549 
550  parent::notify($a_event,$a_ref_id,$a_parent_non_rbac_id,$a_node_id,$a_params);
551  }
552 
559  function isComplete()
560  {
561  if (($this->getTitle()) and (count($this->questions)))
562  {
563  return 1;
564  }
565  else
566  {
567  return 0;
568  }
569  }
570 
577  function _isComplete($obj_id)
578  {
579  $survey = new ilObjSurvey($obj_id, false);
580  $survey->loadFromDb();
581  if (($survey->getTitle()) and (count($survey->questions)))
582  {
583  return 1;
584  }
585  else
586  {
587  return 0;
588  }
589  }
590 
597  function &_getGlobalSurveyData($obj_id)
598  {
599  $survey = new ilObjSurvey($obj_id, false);
600  $survey->loadFromDb();
601  $result = array();
602  if (($survey->getTitle()) and ($survey->author) and (count($survey->questions)))
603  {
604  $result["complete"] = true;
605  }
606  else
607  {
608  $result["complete"] = false;
609  }
610  $result["evaluation_access"] = $survey->getEvaluationAccess();
611  return $result;
612  }
613 
620  {
621  global $ilDB;
622 
623  $complete = 0;
624  if ($this->isComplete())
625  {
626  $complete = 1;
627  }
628  if ($this->getSurveyId() > 0)
629  {
630  $affectedRows = $ilDB->manipulateF("UPDATE svy_svy SET complete = %s, tstamp = %s WHERE survey_id = %s",
631  array('text','integer','integer'),
632  array($this->isComplete(), time(), $this->getSurveyId())
633  );
634  }
635  }
636 
644  function duplicateQuestionForSurvey($question_id, $a_force = false)
645  {
646  global $ilUser;
647 
648  $questiontype = $this->getQuestionType($question_id);
649  $question_gui = $this->getQuestionGUI($questiontype, $question_id);
650 
651  // check if question is a pool question at all, if not do nothing
652  if($this->getId() == $question_gui->object->getObjId() && !$a_force)
653  {
654  return $question_id;
655  }
656 
657  $duplicate_id = $question_gui->object->duplicate(true);
658  return $duplicate_id;
659  }
660 
666  function insertQuestion($question_id)
667  {
668  global $ilDB;
669 
670  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
671  if (!SurveyQuestion::_isComplete($question_id))
672  {
673  return FALSE;
674  }
675  else
676  {
677  // get maximum sequence index in test
678  $result = $ilDB->queryF("SELECT survey_question_id FROM svy_svy_qst WHERE survey_fi = %s",
679  array('integer'),
680  array($this->getSurveyId())
681  );
682  $sequence = $result->numRows();
683  $duplicate_id = $this->duplicateQuestionForSurvey($question_id);
684  $next_id = $ilDB->nextId('svy_svy_qst');
685  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_svy_qst (survey_question_id, survey_fi, question_fi, sequence, tstamp) VALUES (%s, %s, %s, %s, %s)",
686  array('integer', 'integer', 'integer', 'integer', 'integer'),
687  array($next_id, $this->getSurveyId(), $duplicate_id, $sequence, time())
688  );
689  $this->loadQuestionsFromDb();
690  return TRUE;
691  }
692  }
693 
694 
700  function insertQuestionblock($questionblock_id)
701  {
702  global $ilDB;
703  $result = $ilDB->queryF("SELECT svy_qblk.title, svy_qblk.show_questiontext, svy_qblk.show_blocktitle,".
704  " svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst, svy_svy_qst".
705  " WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi".
706  " AND svy_svy_qst.question_fi = svy_qblk_qst.question_fi".
707  " AND svy_qblk.questionblock_id = %s".
708  " ORDER BY svy_svy_qst.sequence",
709  array('integer'),
710  array($questionblock_id)
711  );
712  $questions = array();
713  $show_questiontext = 0;
714  $show_blocktitle = 0;
715  while ($row = $ilDB->fetchAssoc($result))
716  {
717  $duplicate_id = $this->duplicateQuestionForSurvey($row["question_fi"]);
718  array_push($questions, $duplicate_id);
719  $title = $row["title"];
720  $show_questiontext = $row["show_questiontext"];
721  $show_blocktitle = $row["show_blocktitle"];
722  }
723  $this->createQuestionblock($title, $show_questiontext, $show_blocktitle, $questions);
724  }
725 
731  function getAllRTEContent()
732  {
733  $result = array();
734  array_push($result, $this->getIntroduction());
735  array_push($result, $this->getOutro());
736  return $result;
737  }
738 
745  {
746  include_once("./Services/RTE/classes/class.ilRTE.php");
747  $completecontent = "";
748  foreach ($this->getAllRTEContent() as $content)
749  {
750  $completecontent .= $content;
751  }
752  ilRTE::_cleanupMediaObjectUsage($completecontent, $this->getType() . ":html",
753  $this->getId());
754  }
755 
756  public function saveUserSettings($usr_id, $key, $title, $value)
757  {
758  global $ilDB;
759 
760  $next_id = $ilDB->nextId('svy_settings');
761  $affectedRows = $ilDB->insert("svy_settings", array(
762  "settings_id" => array("integer", $next_id),
763  "usr_id" => array("integer", $usr_id),
764  "keyword" => array("text", $key),
765  "title" => array("text", $title),
766  "value" => array("clob", $value)
767  ));
768  }
769 
770  public function deleteUserSettings($id)
771  {
772  global $ilDB;
773 
774  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_settings WHERE settings_id = %s",
775  array('integer'),
776  array($id)
777  );
778  return $affectedRows;
779  }
780 
781  public function getUserSettings($usr_id, $key)
782  {
783  global $ilDB;
784 
785  $result = $ilDB->queryF("SELECT * FROM svy_settings WHERE usr_id = %s AND keyword = %s",
786  array('integer', 'text'),
787  array($usr_id, $key)
788  );
789  $found = array();
790  if ($result->numRows())
791  {
792  while ($row = $ilDB->fetchAssoc($result))
793  {
794  $found[$row['settings_id']] = $row;
795  }
796  }
797  return $found;
798  }
799 
805  function saveToDb()
806  {
807  global $ilDB;
808 
809  // date handling
810  $rmd_start = $this->getReminderStart();
811  if(is_object($rmd_start))
812  {
813  $rmd_start = $rmd_start->get(IL_CAL_DATE);
814  }
815  $rmd_end = $this->getReminderEnd();
816  if(is_object($rmd_end))
817  {
818  $rmd_end = $rmd_end->get(IL_CAL_DATE);
819  }
820 
821  include_once("./Services/RTE/classes/class.ilRTE.php");
822  if ($this->getSurveyId() < 1)
823  {
824  $next_id = $ilDB->nextId('svy_svy');
825  $affectedRows = $ilDB->insert("svy_svy", array(
826  "survey_id" => array("integer", $next_id),
827  "obj_fi" => array("integer", $this->getId()),
828  "author" => array("text", $this->getAuthor()),
829  "introduction" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getIntroduction(), 0)),
830  "outro" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getOutro(), 0)),
831  "status" => array("text", $this->getStatus()),
832  "startdate" => array("text", $this->getStartDate()),
833  "enddate" => array("text", $this->getEndDate()),
834  "evaluation_access" => array("text", $this->getEvaluationAccess()),
835  "invitation" => array("text", $this->getInvitation()),
836  "invitation_mode" => array("text", $this->getInvitationMode()),
837  "complete" => array("text", $this->isComplete()),
838  "created" => array("integer", time()),
839  "anonymize" => array("text", $this->getAnonymize()),
840  "show_question_titles" => array("text", $this->getShowQuestionTitles()),
841  "mailnotification" => array('integer', ($this->getMailNotification()) ? 1 : 0),
842  "mailaddresses" => array('text', strlen($this->getMailAddresses()) ? $this->getMailAddresses() : NULL),
843  "mailparticipantdata" => array('text', strlen($this->getMailParticipantData()) ? $this->getMailParticipantData() : NULL),
844  "tstamp" => array("integer", time()),
845  "template_id" => array("integer", $this->getTemplate()),
846  "pool_usage" => array("integer", $this->getPoolUsage()),
847  // 360°
848  "mode_360" => array("integer", $this->get360Mode()),
849  "mode_360_self_eval" => array("integer", $this->get360SelfEvaluation()),
850  "mode_360_self_rate" => array("integer", $this->get360SelfRaters()),
851  "mode_360_self_appr" => array("integer", $this->get360SelfAppraisee()),
852  "mode_360_results" => array("integer", $this->get360Results()),
853  "mode_360_skill_service" => array("integer", (int) $this->get360SkillService()),
854  // reminder/notification
855  "reminder_status" => array("integer", (int)$this->getReminderStatus()),
856  "reminder_start" => array("datetime", $rmd_start),
857  "reminder_end" => array("datetime", $rmd_end),
858  "reminder_frequency" => array("integer", (int)$this->getReminderFrequency()),
859  "reminder_target" => array("integer", (int)$this->getReminderTarget()),
860  "reminder_last_sent" => array("datetime", $this->getReminderLastSent()),
861  "tutor_ntf_status" => array("integer", (int)$this->getTutorNotificationStatus()),
862  "tutor_ntf_reci" => array("text", implode(";", (array)$this->getTutorNotificationRecipients())),
863  "tutor_ntf_target" => array("integer", (int)$this->getTutorNotificationTarget()),
864  "own_results_view" => array("integer", $this->hasViewOwnResults()),
865  "own_results_mail" => array("integer", $this->hasMailOwnResults())
866  ));
867  $this->setSurveyId($next_id);
868  }
869  else
870  {
871  $affectedRows = $ilDB->update("svy_svy", array(
872  "author" => array("text", $this->getAuthor()),
873  "introduction" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getIntroduction(), 0)),
874  "outro" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getOutro(), 0)),
875  "status" => array("text", $this->getStatus()),
876  "startdate" => array("text", $this->getStartDate()),
877  "enddate" => array("text", $this->getEndDate()),
878  "evaluation_access" => array("text", $this->getEvaluationAccess()),
879  "invitation" => array("text", $this->getInvitation()),
880  "invitation_mode" => array("text", $this->getInvitationMode()),
881  "complete" => array("text", $this->isComplete()),
882  "anonymize" => array("text", $this->getAnonymize()),
883  "show_question_titles" => array("text", $this->getShowQuestionTitles()),
884  "mailnotification" => array('integer', ($this->getMailNotification()) ? 1 : 0),
885  "mailaddresses" => array('text', strlen($this->getMailAddresses()) ? $this->getMailAddresses() : NULL),
886  "mailparticipantdata" => array('text', strlen($this->getMailParticipantData()) ? $this->getMailParticipantData() : NULL),
887  "tstamp" => array("integer", time()),
888  "template_id" => array("integer", $this->getTemplate()),
889  "pool_usage" => array("integer", $this->getPoolUsage()),
890  // 360°
891  "mode_360" => array("integer", $this->get360Mode()),
892  "mode_360_self_eval" => array("integer", $this->get360SelfEvaluation()),
893  "mode_360_self_rate" => array("integer", $this->get360SelfRaters()),
894  "mode_360_self_appr" => array("integer", $this->get360SelfAppraisee()),
895  "mode_360_results" => array("integer", $this->get360Results()),
896  "mode_360_skill_service" => array("integer", (int) $this->get360SkillService()),
897  // reminder/notification
898  "reminder_status" => array("integer", $this->getReminderStatus()),
899  "reminder_start" => array("datetime", $rmd_start),
900  "reminder_end" => array("datetime", $rmd_end),
901  "reminder_frequency" => array("integer", $this->getReminderFrequency()),
902  "reminder_target" => array("integer", $this->getReminderTarget()),
903  "reminder_last_sent" => array("datetime", $this->getReminderLastSent()),
904  "tutor_ntf_status" => array("integer", $this->getTutorNotificationStatus()),
905  "tutor_ntf_reci" => array("text", implode(";", (array)$this->getTutorNotificationRecipients())),
906  "tutor_ntf_target" => array("integer", $this->getTutorNotificationTarget()),
907  "own_results_view" => array("integer", $this->hasViewOwnResults()),
908  "own_results_mail" => array("integer", $this->hasMailOwnResults())
909  ), array(
910  "survey_id" => array("integer", $this->getSurveyId())
911  ));
912  }
913  if ($affectedRows)
914  {
915  // save questions to db
916  $this->saveQuestionsToDb();
917  }
918 
919  // moved activation to ilObjectActivation
920  if($this->ref_id)
921  {
922  include_once "./Services/Object/classes/class.ilObjectActivation.php";
923  ilObjectActivation::getItem($this->ref_id);
924 
925  $item = new ilObjectActivation;
926  if(!$this->isActivationLimited())
927  {
929  }
930  else
931  {
932  $item->setTimingType(ilObjectActivation::TIMINGS_ACTIVATION);
933  $item->setTimingStart($this->getActivationStartDate());
934  $item->setTimingEnd($this->getActivationEndDate());
935  $item->toggleVisible($this->getActivationVisibility());
936  }
937 
938  $item->update($this->ref_id);
939  }
940  }
941 
948  function saveQuestionsToDb()
949  {
950  global $ilDB;
951  // save old questions state
952  $old_questions = array();
953  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE survey_fi = %s",
954  array('integer'),
955  array($this->getSurveyId())
956  );
957  if ($result->numRows())
958  {
959  while ($row = $ilDB->fetchAssoc($result))
960  {
961  $old_questions[$row["question_fi"]] = $row;
962  }
963  }
964 
965  // delete existing question relations
966  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_svy_qst WHERE survey_fi = %s",
967  array('integer'),
968  array($this->getSurveyId())
969  );
970  // create new question relations
971  foreach ($this->questions as $key => $value)
972  {
973  $next_id = $ilDB->nextId('svy_svy_qst');
974  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_svy_qst (survey_question_id, survey_fi, question_fi, heading, sequence, tstamp) VALUES (%s, %s, %s, %s, %s, %s)",
975  array('integer','integer','integer','text','integer','integer'),
976  array($next_id, $this->getSurveyId(), $value, (strlen($old_questions[$value]["heading"])) ? $old_questions[$value]["heading"] : NULL, $key, time())
977  );
978  }
979  }
980 
988  function getAnonymousId($id)
989  {
990  global $ilDB;
991  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_finished WHERE anonymous_id = %s",
992  array('text'),
993  array($id)
994  );
995  if ($result->numRows())
996  {
997  $row = $ilDB->fetchAssoc($result);
998  return $row["anonymous_id"];
999  }
1000  else
1001  {
1002  return "";
1003  }
1004  }
1005 
1012  function getQuestionGUI($questiontype, $question_id)
1013  {
1014  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php";
1015  return SurveyQuestionGUI::_getQuestionGUI($questiontype, $question_id);
1016  }
1017 
1025  function getQuestionType($question_id)
1026  {
1027  global $ilDB;
1028  if ($question_id < 1) return -1;
1029  $result = $ilDB->queryF("SELECT type_tag FROM svy_question, svy_qtype WHERE svy_question.question_id = %s AND " .
1030  "svy_question.questiontype_fi = svy_qtype.questiontype_id",
1031  array('integer'),
1032  array($question_id)
1033  );
1034  if ($result->numRows() == 1)
1035  {
1036  $data = $ilDB->fetchAssoc($result);
1037  return $data["type_tag"];
1038  }
1039  else
1040  {
1041  return "";
1042  }
1043  }
1044 
1051  function getSurveyId()
1052  {
1053  return $this->survey_id;
1054  }
1055 
1059  function setAnonymize($a_anonymize)
1060  {
1061  switch ($a_anonymize)
1062  {
1063  case self::ANONYMIZE_OFF:
1064  case self::ANONYMIZE_ON:
1065  case self::ANONYMIZE_FREEACCESS:
1066  case self::ANONYMIZE_CODE_ALL:
1067  $this->anonymize = $a_anonymize;
1068  break;
1069  default:
1070  $this->anonymize = self::ANONYMIZE_OFF;
1071  break;
1072  }
1073  }
1074 
1080  function getAnonymize()
1081  {
1082  return ($this->anonymize) ? $this->anonymize : 0;
1083  }
1084 
1091  {
1092  return ($this->getAnonymize() == self::ANONYMIZE_OFF ||
1093  $this->getAnonymize() == self::ANONYMIZE_FREEACCESS);
1094  }
1095 
1102  {
1103  return ($this->getAnonymize() == self::ANONYMIZE_ON ||
1104  $this->getAnonymize() == self::ANONYMIZE_FREEACCESS);
1105  }
1106 
1112  function loadFromDb()
1113  {
1114  global $ilDB;
1115  $result = $ilDB->queryF("SELECT * FROM svy_svy WHERE obj_fi = %s",
1116  array('integer'),
1117  array($this->getId())
1118  );
1119  if ($result->numRows() == 1)
1120  {
1121  $data = $ilDB->fetchAssoc($result);
1122  $this->setSurveyId($data["survey_id"]);
1123  $this->setAuthor($data["author"]);
1124  include_once("./Services/RTE/classes/class.ilRTE.php");
1125  $this->setIntroduction(ilRTE::_replaceMediaObjectImageSrc($data["introduction"], 1));
1126  if (strcmp($data["outro"], "survey_finished") == 0)
1127  {
1128  $this->setOutro($this->lng->txt("survey_finished"));
1129  }
1130  else
1131  {
1132  $this->setOutro(ilRTE::_replaceMediaObjectImageSrc($data["outro"], 1));
1133  }
1134  $this->setInvitation($data["invitation"]);
1135  $this->setInvitationMode($data["invitation_mode"]);
1136  $this->setShowQuestionTitles($data["show_question_titles"]);
1137  $this->setStartDate($data["startdate"]);
1138  $this->setEndDate($data["enddate"]);
1139  $this->setAnonymize($data["anonymize"]);
1140  $this->setEvaluationAccess($data["evaluation_access"]);
1141  $this->loadQuestionsFromDb();
1142  $this->setStatus($data["status"]);
1143  $this->setMailNotification($data['mailnotification']);
1144  $this->setMailAddresses($data['mailaddresses']);
1145  $this->setMailParticipantData($data['mailparticipantdata']);
1146  $this->setTemplate($data['template_id']);
1147  $this->setPoolUsage($data['pool_usage']);
1148  // 360°
1149  $this->set360Mode($data['mode_360']);
1150  $this->set360SelfEvaluation($data['mode_360_self_eval']);
1151  $this->set360SelfRaters($data['mode_360_self_rate']);
1152  $this->set360SelfAppraisee($data['mode_360_self_appr']);
1153  $this->set360Results($data['mode_360_results']);
1154  $this->set360SkillService($data['mode_360_skill_service']);
1155  // reminder/notification
1156  $this->setReminderStatus($data["reminder_status"]);
1157  $this->setReminderStart($data["reminder_start"] ? new ilDate($data["reminder_start"], IL_CAL_DATE) : null);
1158  $this->setReminderEnd($data["reminder_end"] ? new ilDate($data["reminder_end"], IL_CAL_DATE) : null);
1159  $this->setReminderFrequency($data["reminder_frequency"]);
1160  $this->setReminderTarget($data["reminder_target"]);
1161  $this->setReminderLastSent($data["reminder_last_sent"]);
1162  $this->setTutorNotificationStatus($data["tutor_ntf_status"]);
1163  $this->setTutorNotificationRecipients(explode(";", $data["tutor_ntf_reci"]));
1164  $this->setTutorNotificationTarget($data["tutor_ntf_target"]);
1165 
1166  $this->setViewOwnResults($data["own_results_view"]);
1167  $this->setMailOwnResults($data["own_results_mail"]);
1168  }
1169 
1170  // moved activation to ilObjectActivation
1171  if($this->ref_id)
1172  {
1173  include_once "./Services/Object/classes/class.ilObjectActivation.php";
1174  $activation = ilObjectActivation::getItem($this->ref_id);
1175  switch($activation["timing_type"])
1176  {
1178  $this->setActivationLimited(true);
1179  $this->setActivationStartDate($activation["timing_start"]);
1180  $this->setActivationEndDate($activation["timing_end"]);
1181  $this->setActivationVisibility($activation["visible"]);
1182  break;
1183 
1184  default:
1185  $this->setActivationLimited(false);
1186  break;
1187  }
1188  }
1189  }
1190 
1198  {
1199  global $ilDB;
1200  $this->questions = array();
1201  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE survey_fi = %s ORDER BY sequence",
1202  array('integer'),
1203  array($this->getSurveyId())
1204  );
1205  while ($data = $ilDB->fetchAssoc($result))
1206  {
1207  $this->questions[$data["sequence"]] = $data["question_fi"];
1208  }
1209  }
1210 
1218  function setAuthor($author = "")
1219  {
1220  $this->author = $author;
1221  }
1222 
1232  function saveAuthorToMetadata($a_author = "")
1233  {
1234  $md =& new ilMD($this->getId(), 0, $this->getType());
1235  $md_life =& $md->getLifecycle();
1236  if (!$md_life)
1237  {
1238  if (strlen($a_author) == 0)
1239  {
1240  global $ilUser;
1241  $a_author = $ilUser->getFullname();
1242  }
1243 
1244  $md_life =& $md->addLifecycle();
1245  $md_life->save();
1246  $con =& $md_life->addContribute();
1247  $con->setRole("Author");
1248  $con->save();
1249  $ent =& $con->addEntity();
1250  $ent->setEntity($a_author);
1251  $ent->save();
1252  }
1253  }
1254 
1262  function getAuthor()
1263  {
1264  $author = array();
1265  include_once "./Services/MetaData/classes/class.ilMD.php";
1266  $md =& new ilMD($this->getId(), 0, $this->getType());
1267  $md_life =& $md->getLifecycle();
1268  if ($md_life)
1269  {
1270  $ids =& $md_life->getContributeIds();
1271  foreach ($ids as $id)
1272  {
1273  $md_cont =& $md_life->getContribute($id);
1274  if (strcmp($md_cont->getRole(), "Author") == 0)
1275  {
1276  $entids =& $md_cont->getEntityIds();
1277  foreach ($entids as $entid)
1278  {
1279  $md_ent =& $md_cont->getEntity($entid);
1280  array_push($author, $md_ent->getEntity());
1281  }
1282  }
1283  }
1284  }
1285  return join($author, ",");
1286  }
1287 
1294  public function getShowQuestionTitles()
1295  {
1296  return ($this->display_question_titles) ? 1 : 0;
1297  }
1298 
1305  public function setShowQuestionTitles($a_show)
1306  {
1307  $this->display_question_titles = ($a_show) ? 1 : 0;
1308  }
1309 
1317  {
1318  $this->display_question_titles = 1;
1319  }
1320 
1328  {
1329  $this->display_question_titles = 0;
1330  }
1331 
1339  function setInvitation($invitation = 0)
1340  {
1341  global $ilDB, $ilAccess;
1342 
1343  $this->invitation = $invitation;
1344  if ($invitation == self::INVITATION_OFF)
1345  {
1346  $this->disinviteAllUsers();
1347  }
1348  else if ($invitation == self::INVITATION_ON)
1349  {
1350  if ($this->getInvitationMode() == self::MODE_UNLIMITED)
1351  {
1352  $result = $ilDB->query("SELECT usr_id FROM usr_data");
1353  while ($row = $ilDB->fetchAssoc($result))
1354  {
1355  if ($ilAccess->checkAccessOfUser($row["usr_id"], "read", "", $this->getRefId(), "svy", $this->getId()))
1356  {
1357  $this->inviteUser($row['usr_id']);
1358  }
1359  }
1360  }
1361  }
1362  }
1363 
1371  function setInvitationMode($invitation_mode = 0)
1372  {
1373  $this->invitation_mode = $invitation_mode;
1374  }
1375 
1384  function setInvitationAndMode($invitation = 0, $invitation_mode = 0)
1385  {
1386  $this->invitation_mode = $invitation_mode;
1387  $this->setInvitation($invitation);
1388  }
1389 
1396  public function setIntroduction($introduction = "")
1397  {
1398  $this->introduction = $introduction;
1399  }
1400 
1407  public function setOutro($outro = "")
1408  {
1409  $this->outro = $outro;
1410  }
1411 
1419  function getInvitation()
1420  {
1421  return ($this->invitation) ? $this->invitation : self::INVITATION_OFF;
1422  }
1423 
1431  function getInvitationMode()
1432  {
1433  include_once "./Services/Administration/classes/class.ilSetting.php";
1434  $surveySetting = new ilSetting("survey");
1435  $unlimited_invitation = $surveySetting->get("unlimited_invitation");
1436  if (!$unlimited_invitation && $this->invitation_mode == self::MODE_UNLIMITED)
1437  {
1438  return self::MODE_PREDEFINED_USERS;
1439  }
1440  else
1441  {
1442  return ($this->invitation_mode) ? $this->invitation_mode : self::MODE_UNLIMITED;
1443  }
1444  }
1445 
1453  function getStatus()
1454  {
1455  return ($this->status) ? $this->status : self::STATUS_OFFLINE;
1456  }
1457 
1465  function isOnline()
1466  {
1467  return ($this->status == self::STATUS_ONLINE) ? true : false;
1468  }
1469 
1477  function isOffline()
1478  {
1479  return ($this->status == self::STATUS_OFFLINE) ? true : false;
1480  }
1481 
1490  function setStatus($status = self::STATUS_OFFLINE)
1491  {
1492  $result = "";
1493  if (($status == self::STATUS_ONLINE) && (count($this->questions) == 0))
1494  {
1495  $this->status = self::STATUS_OFFLINE;
1496  $result = $this->lng->txt("cannot_switch_to_online_no_questions");
1497  }
1498  else
1499  {
1500  $this->status = $status;
1501  }
1502  return $result;
1503  }
1504 
1512  function getStartDate()
1513  {
1514  return (strlen($this->start_date)) ? $this->start_date : NULL;
1515  }
1516 
1523  function canStartSurvey($anonymous_id = NULL, $a_no_rbac = false)
1524  {
1525  global $ilAccess;
1526 
1527  $result = TRUE;
1528  $messages = array();
1529  $edit_settings = false;
1530  // check start date
1531  if (preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getStartDate(), $matches))
1532  {
1533  $epoch_time = mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1534  $now = mktime();
1535  if ($now < $epoch_time)
1536  {
1537  array_push($messages,$this->lng->txt('start_date_not_reached').' ('.
1539  $result = FALSE;
1540  $edit_settings = true;
1541  }
1542  }
1543  // check end date
1544  if (preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getEndDate(), $matches))
1545  {
1546  $epoch_time = mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1547  $now = mktime();
1548  if ($now > $epoch_time)
1549  {
1550  array_push($messages,$this->lng->txt('end_date_reached').' ('.
1552  $result = FALSE;
1553  $edit_settings = true;
1554  }
1555  }
1556 
1557  // check online status
1558  if ($this->getStatus() == self::STATUS_OFFLINE)
1559  {
1560  array_push($messages, $this->lng->txt("survey_is_offline"));
1561  $result = FALSE;
1562  $edit_settings = true;
1563  }
1564  // check rbac permissions
1565  if (!$a_no_rbac && !$ilAccess->checkAccess("read", "", $this->ref_id))
1566  {
1567  array_push($messages, $this->lng->txt("cannot_participate_survey"));
1568  $result = FALSE;
1569  }
1570  /*
1571  // 2. check previous access
1572  if (!$result["error"])
1573  {
1574  global $ilUser;
1575  $survey_started = $this->isSurveyStarted($ilUser->getId(), $anonymous_id);
1576  if ($survey_started === 1)
1577  {
1578  array_push($messages, $this->lng->txt("already_completed_survey"));
1579  $result = FALSE;
1580  }
1581  }
1582  */
1583  return array(
1584  "result" => $result,
1585  "messages" => $messages,
1586  "edit_settings" => $edit_settings
1587  );
1588  }
1589 
1597  function setStartDate($start_date = "")
1598  {
1599  $this->start_date = $start_date;
1600  }
1601 
1610  function setStartDateAndTime($start_date = "", $start_time)
1611  {
1612  $y = ''; $m = ''; $d = ''; $h = ''; $i = ''; $s = '';
1613  if (preg_match("/(\d{4})-(\d{2})-(\d{2})/", $start_date, $matches))
1614  {
1615  $y = $matches[1];
1616  $m = $matches[2];
1617  $d = $matches[3];
1618  }
1619  if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $start_time, $matches))
1620  {
1621  $h = $matches[1];
1622  $i = $matches[2];
1623  $s = $matches[3];
1624  }
1625  $this->start_date = sprintf('%04d%02d%02d%02d%02d%02d', $y, $m, $d, $h, $i, $s);
1626  }
1627 
1635  function getEndDate()
1636  {
1637  return (strlen($this->end_date)) ? $this->end_date : NULL;
1638  }
1639 
1647  function setEndDate($end_date = "")
1648  {
1649  $this->end_date = $end_date;
1650  }
1651 
1660  function setEndDateAndTime($end_date = "", $end_time)
1661  {
1662  $y = ''; $m = ''; $d = ''; $h = ''; $i = ''; $s = '';
1663  if (preg_match("/(\d{4})-(\d{2})-(\d{2})/", $end_date, $matches))
1664  {
1665  $y = $matches[1];
1666  $m = $matches[2];
1667  $d = $matches[3];
1668  }
1669  if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $end_time, $matches))
1670  {
1671  $h = $matches[1];
1672  $i = $matches[2];
1673  $s = $matches[3];
1674  }
1675  $this->end_date = sprintf('%04d%02d%02d%02d%02d%02d', $y, $m, $d, $h, $i, $s);
1676  }
1677 
1686  {
1687  return ($this->evaluation_access) ? $this->evaluation_access : self::EVALUATION_ACCESS_OFF;
1688  }
1689 
1697  function setEvaluationAccess($evaluation_access = self::EVALUATION_ACCESS_OFF)
1698  {
1699  $this->evaluation_access = ($evaluation_access) ? $evaluation_access : self::EVALUATION_ACCESS_OFF;
1700  }
1701 
1702  function setActivationVisibility($a_value)
1703  {
1704  $this->activation_visibility = (bool) $a_value;
1705  }
1706 
1708  {
1710  }
1711 
1713  {
1714  return (bool)$this->activation_limited;
1715  }
1716 
1717  function setActivationLimited($a_value)
1718  {
1719  $this->activation_limited = (bool)$a_value;
1720  }
1721 
1729  function getIntroduction()
1730  {
1731  return (strlen($this->introduction)) ? $this->introduction : NULL;
1732  }
1733 
1741  function getOutro()
1742  {
1743  return (strlen($this->outro)) ? $this->outro : NULL;
1744  }
1745 
1753  {
1754  global $ilDB;
1755  $existing_questions = array();
1756  $result = $ilDB->queryF("SELECT svy_question.original_id FROM svy_question, svy_svy_qst WHERE " .
1757  "svy_svy_qst.survey_fi = %s AND svy_svy_qst.question_fi = svy_question.question_id",
1758  array('integer'),
1759  array($this->getSurveyId())
1760  );
1761  while ($data = $ilDB->fetchAssoc($result))
1762  {
1763  if($data["original_id"])
1764  {
1765  array_push($existing_questions, $data["original_id"]);
1766  }
1767  }
1768  return $existing_questions;
1769  }
1770 
1777  function &getQuestionpoolTitles($could_be_offline = FALSE, $showPath = FALSE)
1778  {
1779  include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php";
1780  return ilObjSurveyQuestionPool::_getAvailableQuestionpools($use_object_id = TRUE, $could_be_offline, $showPath);
1781  }
1782 
1789  function moveUpQuestion($question_id)
1790  {
1791  $move_questions = array($question_id);
1792  $pages =& $this->getSurveyPages();
1793  $pageindex = -1;
1794  foreach ($pages as $idx => $page)
1795  {
1796  if ($page[0]["question_id"] == $question_id)
1797  {
1798  $pageindex = $idx;
1799  }
1800  }
1801  if ($pageindex > 0)
1802  {
1803  $this->moveQuestions($move_questions, $pages[$pageindex-1][0]["question_id"], 0);
1804  }
1805  else
1806  {
1807  // move up a question in a questionblock
1808  $questions = $this->getSurveyQuestions();
1809  $questions = array_keys($questions);
1810  $index = array_search($question_id, $questions);
1811  if (($index !== FALSE) && ($index > 0))
1812  {
1813  $this->moveQuestions($move_questions, $questions[$index-1], 0);
1814  }
1815  }
1816  }
1817 
1823  public function moveDownQuestion($question_id)
1824  {
1825  $move_questions = array($question_id);
1826  $pages =& $this->getSurveyPages();
1827  $pageindex = -1;
1828  foreach ($pages as $idx => $page)
1829  {
1830  if (($page[0]["question_id"] == $question_id) && (strcmp($page[0]["questionblock_id"], "") == 0))
1831  {
1832  $pageindex = $idx;
1833  }
1834  }
1835  if (($pageindex < count($pages)-1) && ($pageindex >= 0))
1836  {
1837  $this->moveQuestions($move_questions, $pages[$pageindex+1][count($pages[$pageindex+1])-1]["question_id"], 1);
1838  }
1839  else
1840  {
1841  // move down a question in a questionblock
1842  $questions = $this->getSurveyQuestions();
1843  $questions = array_keys($questions);
1844  $index = array_search($question_id, $questions);
1845  if (($index !== FALSE) && ($index < count($questions)-1))
1846  {
1847  $this->moveQuestions($move_questions, $questions[$index+1], 1);
1848  }
1849  }
1850  }
1851 
1858  function moveUpQuestionblock($questionblock_id)
1859  {
1860  $pages =& $this->getSurveyPages();
1861  $move_questions = array();
1862  $pageindex = -1;
1863  foreach ($pages as $idx => $page)
1864  {
1865  if ($page[0]["questionblock_id"] == $questionblock_id)
1866  {
1867  foreach ($page as $pageidx => $question)
1868  {
1869  array_push($move_questions, $question["question_id"]);
1870  }
1871  $pageindex = $idx;
1872  }
1873  }
1874  if ($pageindex > 0)
1875  {
1876  $this->moveQuestions($move_questions, $pages[$pageindex-1][0]["question_id"], 0);
1877  }
1878  }
1879 
1886  function moveDownQuestionblock($questionblock_id)
1887  {
1888  $pages =& $this->getSurveyPages();
1889  $move_questions = array();
1890  $pageindex = -1;
1891  foreach ($pages as $idx => $page)
1892  {
1893  if ($page[0]["questionblock_id"] == $questionblock_id)
1894  {
1895  foreach ($page as $pageidx => $question)
1896  {
1897  array_push($move_questions, $question["question_id"]);
1898  }
1899  $pageindex = $idx;
1900  }
1901  }
1902  if ($pageindex < count($pages)-1)
1903  {
1904  $this->moveQuestions($move_questions, $pages[$pageindex+1][count($pages[$pageindex+1])-1]["question_id"], 1);
1905  }
1906  }
1907 
1916  function moveQuestions($move_questions, $target_index, $insert_mode)
1917  {
1918  $array_pos = array_search($target_index, $this->questions);
1919  if ($insert_mode == 0)
1920  {
1921  $part1 = array_slice($this->questions, 0, $array_pos);
1922  $part2 = array_slice($this->questions, $array_pos);
1923  }
1924  else if ($insert_mode == 1)
1925  {
1926  $part1 = array_slice($this->questions, 0, $array_pos + 1);
1927  $part2 = array_slice($this->questions, $array_pos + 1);
1928  }
1929  foreach ($move_questions as $question_id)
1930  {
1931  if (!(array_search($question_id, $part1) === FALSE))
1932  {
1933  unset($part1[array_search($question_id, $part1)]);
1934  }
1935  if (!(array_search($question_id, $part2) === FALSE))
1936  {
1937  unset($part2[array_search($question_id, $part2)]);
1938  }
1939  }
1940  $part1 = array_values($part1);
1941  $part2 = array_values($part2);
1942  $this->questions = array_values(array_merge($part1, $move_questions, $part2));
1943  foreach ($move_questions as $question_id)
1944  {
1945  $constraints = $this->getConstraints($question_id);
1946  foreach ($constraints as $idx => $constraint)
1947  {
1948  foreach ($part2 as $next_question_id)
1949  {
1950  if ($constraint["question"] == $next_question_id)
1951  {
1952  // constraint concerning a question that follows -> delete constraint
1953  $this->deleteConstraint($constraint["id"]);
1954  }
1955  }
1956  }
1957  }
1958  $this->saveQuestionsToDb();
1959  }
1960 
1967  function removeQuestion($question_id)
1968  {
1969  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
1970  $question =& $this->_instanciateQuestion($question_id);
1971  #20610 if no question found, do nothing.
1972  if($question)
1973  {
1974  $question->delete($question_id);
1975  $this->removeConstraintsConcerningQuestion($question_id);
1976  }
1977  }
1978 
1986  {
1987  global $ilDB;
1988  $result = $ilDB->queryF("SELECT constraint_fi FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s",
1989  array('integer','integer'),
1990  array($question_id, $this->getSurveyId())
1991  );
1992  if ($result->numRows() > 0)
1993  {
1994  $remove_constraints = array();
1995  while ($row = $ilDB->fetchAssoc($result))
1996  {
1997  array_push($remove_constraints, $row["constraint_fi"]);
1998  }
1999  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s",
2000  array('integer','integer'),
2001  array($question_id, $this->getSurveyId())
2002  );
2003  foreach ($remove_constraints as $key => $constraint_id)
2004  {
2005  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_constraint WHERE constraint_id = %s",
2006  array('integer'),
2007  array($constraint_id)
2008  );
2009  }
2010  }
2011  }
2012 
2020  function removeQuestions($remove_questions, $remove_questionblocks)
2021  {
2022  global $ilDB;
2023 
2024  $block_sizes = array();
2025  foreach ($this->getSurveyQuestions() as $question_id => $data)
2026  {
2027  if (in_array($question_id, $remove_questions) or in_array($data["questionblock_id"], $remove_questionblocks))
2028  {
2029  unset($this->questions[array_search($question_id, $this->questions)]);
2030  $this->removeQuestion($question_id);
2031  }
2032  else if($data["questionblock_id"])
2033  {
2034  $block_sizes[$data["questionblock_id"]]++;
2035  }
2036  }
2037 
2038  // blocks with just 1 question need to be deleted
2039  foreach($block_sizes as $block_id => $size)
2040  {
2041  if($size < 2)
2042  {
2043  $remove_questionblocks[] = $block_id;
2044  }
2045  }
2046 
2047  foreach (array_unique($remove_questionblocks) as $questionblock_id)
2048  {
2049  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk WHERE questionblock_id = %s",
2050  array('integer'),
2051  array($questionblock_id)
2052  );
2053  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s",
2054  array('integer','integer'),
2055  array($questionblock_id, $this->getSurveyId())
2056  );
2057  }
2058 
2059  $this->questions = array_values($this->questions);
2060  $this->saveQuestionsToDb();
2061  }
2062 
2069  function unfoldQuestionblocks($questionblocks)
2070  {
2071  global $ilDB;
2072  foreach ($questionblocks as $index)
2073  {
2074  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk WHERE questionblock_id = %s",
2075  array('integer'),
2076  array($index)
2077  );
2078  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s",
2079  array('integer','integer'),
2080  array($index, $this->getSurveyId())
2081  );
2082  }
2083  }
2084 
2085  function removeQuestionFromBlock($question_id, $questionblock_id)
2086  {
2087  global $ilDB;
2088 
2089  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s AND question_fi = %s",
2090  array('integer','integer','integer'),
2091  array($questionblock_id, $this->getSurveyId(), $question_id)
2092  );
2093  }
2094 
2095  function addQuestionToBlock($question_id, $questionblock_id)
2096  {
2097  global $ilDB;
2098 
2099 
2100  $next_id = $ilDB->nextId('svy_qblk_qst');
2101  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, " .
2102  "question_fi) VALUES (%s, %s, %s, %s)",
2103  array('integer','integer','integer','integer'),
2104  array($next_id, $this->getSurveyId(), $questionblock_id, $question_id)
2105  );
2106 
2107  $this->deleteConstraints($question_id); // #13713
2108  }
2109 
2116  function &getQuestionblockQuestions($questionblock_id)
2117  {
2118  global $ilDB;
2119  $titles = array();
2120  $result = $ilDB->queryF("SELECT svy_question.title, svy_qblk_qst.question_fi, svy_qblk_qst.survey_fi FROM ".
2121  "svy_qblk, svy_qblk_qst, svy_question WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND " .
2122  "svy_question.question_id = svy_qblk_qst.question_fi AND svy_qblk.questionblock_id = %s",
2123  array('integer'),
2124  array($questionblock_id)
2125  );
2126  $survey_id = "";
2127  while ($row = $ilDB->fetchAssoc($result))
2128  {
2129  $titles[$row["question_fi"]] = $row["title"];
2130  $survey_id = $row["survey_fi"];
2131  }
2132  $result = $ilDB->queryF("SELECT question_fi, sequence FROM svy_svy_qst WHERE survey_fi = %s ORDER BY sequence",
2133  array('integer'),
2134  array($survey_id)
2135  );
2136  $resultarray = array();
2137  $counter = 1;
2138  while ($row = $ilDB->fetchAssoc($result))
2139  {
2140  if (array_key_exists($row["question_fi"], $titles))
2141  {
2142  $resultarray[$counter++] = $titles[$row["question_fi"]];
2143  }
2144  }
2145  return $resultarray;
2146  }
2147 
2154  function &getQuestionblockQuestionIds($questionblock_id)
2155  {
2156  global $ilDB;
2157 
2158  // we need a correct order here, see #22011
2159  $result = $ilDB->queryF("SELECT a.question_fi FROM svy_qblk_qst a JOIN svy_svy_qst b ON (a.question_fi = b.question_fi) ".
2160  " WHERE a.questionblock_fi = %s ORDER BY b.sequence",
2161  array("integer"),
2162  array($questionblock_id)
2163  );
2164  $ids = array();
2165  if ($result->numRows())
2166  {
2167  while ($data = $ilDB->fetchAssoc($result))
2168  {
2169  if (!in_array($data['question_fi'], $ids)) // no duplicates, see #22018
2170  {
2171  array_push($ids, $data['question_fi']);
2172  }
2173  }
2174  }
2175 
2176  return $ids;
2177  }
2178 
2186  function getQuestionblock($questionblock_id)
2187  {
2188  global $ilDB;
2189  $result = $ilDB->queryF("SELECT * FROM svy_qblk WHERE questionblock_id = %s",
2190  array('integer'),
2191  array($questionblock_id)
2192  );
2193  return $ilDB->fetchAssoc($result);
2194  }
2195 
2203  function _getQuestionblock($questionblock_id)
2204  {
2205  global $ilDB;
2206  $result = $ilDB->queryF("SELECT * FROM svy_qblk WHERE questionblock_id = %s",
2207  array('integer'),
2208  array($questionblock_id)
2209  );
2210  $row = $ilDB->fetchAssoc($result);
2211  return $row;
2212  }
2213 
2222  function _addQuestionblock($title = "", $owner = 0, $show_questiontext = true, $show_blocktitle = false)
2223  {
2224  global $ilDB;
2225  $next_id = $ilDB->nextId('svy_qblk');
2226  $ilDB->manipulateF("INSERT INTO svy_qblk (questionblock_id, title, show_questiontext,".
2227  " show_blocktitle, owner_fi, tstamp) " .
2228  "VALUES (%s, %s, %s, %s, %s, %s)",
2229  array('integer','text','integer','integer','integer','integer'),
2230  array($next_id, $title, $show_questiontext, $show_blocktitle, $owner, time())
2231  );
2232  return $next_id;
2233  }
2234 
2242  function createQuestionblock($title, $show_questiontext, $show_blocktitle, $questions)
2243  {
2244  global $ilDB;
2245 
2246  // if the selected questions are not in a continous selection, move all questions of the
2247  // questionblock at the position of the first selected question
2248  $this->moveQuestions($questions, $questions[0], 0);
2249 
2250  // now save the question block
2251  global $ilUser;
2252  $next_id = $ilDB->nextId('svy_qblk');
2253  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk (questionblock_id, title, show_questiontext,".
2254  " show_blocktitle, owner_fi, tstamp) VALUES (%s, %s, %s, %s, %s, %s)",
2255  array('integer','text','text','text','integer','integer'),
2256  array($next_id, $title, $show_questiontext, $show_blocktitle, $ilUser->getId(), time())
2257  );
2258  if ($affectedRows)
2259  {
2260  $questionblock_id = $next_id;
2261  foreach ($questions as $index)
2262  {
2263  $next_id = $ilDB->nextId('svy_qblk_qst');
2264  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, " .
2265  "question_fi) VALUES (%s, %s, %s, %s)",
2266  array('integer','integer','integer','integer'),
2267  array($next_id, $this->getSurveyId(), $questionblock_id, $index)
2268  );
2269  $this->deleteConstraints($index);
2270  }
2271  }
2272  }
2273 
2281  function modifyQuestionblock($questionblock_id, $title, $show_questiontext, $show_blocktitle)
2282  {
2283  global $ilDB;
2284  $affectedRows = $ilDB->manipulateF("UPDATE svy_qblk SET title = %s, show_questiontext = %s,".
2285  " show_blocktitle = %s WHERE questionblock_id = %s",
2286  array('text','text','text','integer'),
2287  array($title, $show_questiontext, $show_blocktitle, $questionblock_id)
2288  );
2289  }
2290 
2297  function deleteConstraints($question_id)
2298  {
2299  global $ilDB;
2300  $result = $ilDB->queryF("SELECT constraint_fi FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s",
2301  array('integer','integer'),
2302  array($question_id, $this->getSurveyId())
2303  );
2304  $constraints = array();
2305  while ($row = $ilDB->fetchAssoc($result))
2306  {
2307  array_push($constraints, $row["constraint_fi"]);
2308  }
2309  foreach ($constraints as $constraint_id)
2310  {
2311  $this->deleteConstraint($constraint_id);
2312  }
2313  }
2314 
2322  function deleteConstraint($constraint_id)
2323  {
2324  global $ilDB;
2325  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_constraint WHERE constraint_id = %s",
2326  array('integer'),
2327  array($constraint_id)
2328  );
2329  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_constraint WHERE constraint_fi = %s",
2330  array('integer'),
2331  array($constraint_id)
2332  );
2333  }
2334 
2340  public function &getSurveyQuestions($with_answers = false)
2341  {
2342  global $ilDB;
2343  $obligatory_states =& $this->getObligatoryStates();
2344  // get questionblocks
2345  $all_questions = array();
2346  $result = $ilDB->queryF("SELECT svy_qtype.type_tag, svy_qtype.plugin, svy_question.question_id, ".
2347  "svy_svy_qst.heading FROM svy_qtype, svy_question, svy_svy_qst WHERE svy_svy_qst.survey_fi = %s AND " .
2348  "svy_svy_qst.question_fi = svy_question.question_id AND svy_question.questiontype_fi = svy_qtype.questiontype_id " .
2349  "ORDER BY svy_svy_qst.sequence",
2350  array('integer'),
2351  array($this->getSurveyId())
2352  );
2353  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
2354  while ($row = $ilDB->fetchAssoc($result))
2355  {
2356  $add = true;
2357  if ($row["plugin"])
2358  {
2359  if (!$this->isPluginActive($row["type_tag"]))
2360  {
2361  $add = false;
2362  }
2363  }
2364  if ($add)
2365  {
2366  $question =& $this->_instanciateQuestion($row["question_id"]);
2367  $questionrow = $question->_getQuestionDataArray($row["question_id"]);
2368  foreach ($row as $key => $value)
2369  {
2370  $questionrow[$key] = $value;
2371  }
2372  $all_questions[$row["question_id"]] = $questionrow;
2373  $all_questions[$row["question_id"]]["usableForPrecondition"] = $question->usableForPrecondition();
2374  $all_questions[$row["question_id"]]["availableRelations"] = $question->getAvailableRelations();
2375  if (array_key_exists($row["question_id"], $obligatory_states))
2376  {
2377  $all_questions[$row["question_id"]]["obligatory"] = $obligatory_states[$row["question_id"]];
2378  }
2379  }
2380  }
2381  // get all questionblocks
2382  $questionblocks = array();
2383  if (count($all_questions))
2384  {
2385  $result = $ilDB->queryF("SELECT svy_qblk.*, svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst WHERE " .
2386  "svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_qblk_qst.survey_fi = %s " .
2387  "AND " . $ilDB->in('svy_qblk_qst.question_fi', array_keys($all_questions), false, 'integer'),
2388  array('integer'),
2389  array($this->getSurveyId())
2390  );
2391  while ($row = $ilDB->fetchAssoc($result))
2392  {
2393  $questionblocks[$row['question_fi']] = $row;
2394  }
2395  }
2396 
2397  foreach ($all_questions as $question_id => $row)
2398  {
2399  $constraints = $this->getConstraints($question_id);
2400  if (isset($questionblocks[$question_id]))
2401  {
2402  $all_questions[$question_id]["questionblock_title"] = $questionblocks[$question_id]['title'];
2403  $all_questions[$question_id]["questionblock_id"] = $questionblocks[$question_id]['questionblock_id'];
2404  $all_questions[$question_id]["constraints"] = $constraints;
2405  }
2406  else
2407  {
2408  $all_questions[$question_id]["questionblock_title"] = "";
2409  $all_questions[$question_id]["questionblock_id"] = "";
2410  $all_questions[$question_id]["constraints"] = $constraints;
2411  }
2412  if ($with_answers)
2413  {
2414  $answers = array();
2415  $result = $ilDB->queryF("SELECT svy_variable.*, svy_category.title FROM svy_variable, svy_category " .
2416  "WHERE svy_variable.question_fi = %s AND svy_variable.category_fi = svy_category.category_id ".
2417  "ORDER BY sequence ASC",
2418  array('integer'),
2419  array($question_id)
2420  );
2421  if ($result->numRows() > 0)
2422  {
2423  while ($data = $ilDB->fetchAssoc($result))
2424  {
2425  array_push($answers, $data["title"]);
2426  }
2427  }
2428  $all_questions[$question_id]["answers"] = $answers;
2429  }
2430  }
2431  return $all_questions;
2432  }
2433 
2440  function setObligatoryStates($obligatory_questions)
2441  {
2442  global $ilDB;
2443  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE survey_fi = %s",
2444  array('integer'),
2445  array($this->getSurveyId())
2446  );
2447  if ($result->numRows())
2448  {
2449  while ($row = $ilDB->fetchAssoc($result))
2450  {
2451  if (!array_key_exists($row["question_fi"], $obligatory_questions))
2452  {
2453  $obligatory_questions[$row["question_fi"]] = 0;
2454  }
2455  }
2456  }
2457 
2458  // set the obligatory states in the database
2459  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_oblig WHERE survey_fi = %s",
2460  array('integer'),
2461  array($this->getSurveyId())
2462  );
2463 
2464  // set the obligatory states in the database
2465  foreach ($obligatory_questions as $question_fi => $obligatory)
2466  {
2467  $next_id = $ilDB->nextId('svy_qst_oblig');
2468  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qst_oblig (question_obligatory_id, survey_fi, question_fi, " .
2469  "obligatory, tstamp) VALUES (%s, %s, %s, %s, %s)",
2470  array('integer','integer','integer','text','integer'),
2471  array($next_id, $this->getSurveyId(), $question_fi, (strlen($obligatory)) ? $obligatory : 0, time())
2472  );
2473 
2474  // #12420
2475  $ilDB->manipulate("UPDATE svy_question".
2476  " SET obligatory = ".$ilDB->quote($obligatory, "integer").
2477  " WHERE question_id = ".$ilDB->quote($question_fi, "integer"));
2478  }
2479  }
2480 
2488  {
2489  global $ilDB;
2490  $obligatory_states = array();
2491  $result = $ilDB->queryF("SELECT * FROM svy_qst_oblig WHERE survey_fi = %s",
2492  array('integer'),
2493  array($this->getSurveyId())
2494  );
2495  if ($result->numRows())
2496  {
2497  while ($row = $ilDB->fetchAssoc($result))
2498  {
2499  $obligatory_states[$row["question_fi"]] = $row["obligatory"];
2500  }
2501  }
2502  return $obligatory_states;
2503  }
2504 
2510  function &getSurveyPages()
2511  {
2512  global $ilDB;
2513  $obligatory_states =& $this->getObligatoryStates();
2514  // get questionblocks
2515  $all_questions = array();
2516  $result = $ilDB->queryF("SELECT svy_question.*, svy_qtype.type_tag, svy_svy_qst.heading FROM " .
2517  "svy_question, svy_qtype, svy_svy_qst WHERE svy_svy_qst.survey_fi = %s AND " .
2518  "svy_svy_qst.question_fi = svy_question.question_id AND svy_question.questiontype_fi = svy_qtype.questiontype_id ".
2519  "ORDER BY svy_svy_qst.sequence",
2520  array('integer'),
2521  array($this->getSurveyId())
2522  );
2523  while ($row = $ilDB->fetchAssoc($result))
2524  {
2525  $all_questions[$row["question_id"]] = $row;
2526  }
2527  // get all questionblocks
2528  $questionblocks = array();
2529  if (count($all_questions))
2530  {
2531  $result = $ilDB->queryF("SELECT svy_qblk.*, svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst ".
2532  "WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_qblk_qst.survey_fi = %s ".
2533  "AND " . $ilDB->in('svy_qblk_qst.question_fi', array_keys($all_questions), false, 'integer'),
2534  array('integer'),
2535  array($this->getSurveyId())
2536  );
2537  while ($row = $ilDB->fetchAssoc($result))
2538  {
2539  $questionblocks[$row['question_fi']] = $row;
2540  }
2541  }
2542 
2543  $all_pages = array();
2544  $pageindex = -1;
2545  $currentblock = "";
2546  foreach ($all_questions as $question_id => $row)
2547  {
2548  if (array_key_exists($question_id, $obligatory_states))
2549  {
2550  $all_questions[$question_id]["obligatory"] = $obligatory_states[$question_id];
2551  }
2552  $constraints = array();
2553  if (isset($questionblocks[$question_id]))
2554  {
2555  if (!$currentblock or ($currentblock != $questionblocks[$question_id]['questionblock_id']))
2556  {
2557  $pageindex++;
2558  }
2559  $all_questions[$question_id]['page'] = $pageindex;
2560  $all_questions[$question_id]["questionblock_title"] = $questionblocks[$question_id]['title'];
2561  $all_questions[$question_id]["questionblock_id"] = $questionblocks[$question_id]['questionblock_id'];
2562  $all_questions[$question_id]["questionblock_show_questiontext"] = $questionblocks[$question_id]['show_questiontext'];
2563  $all_questions[$question_id]["questionblock_show_blocktitle"] = $questionblocks[$question_id]['show_blocktitle'];
2564  $currentblock = $questionblocks[$question_id]['questionblock_id'];
2565  $constraints = $this->getConstraints($question_id);
2566  $all_questions[$question_id]["constraints"] = $constraints;
2567  }
2568  else
2569  {
2570  $pageindex++;
2571  $all_questions[$question_id]['page'] = $pageindex;
2572  $all_questions[$question_id]["questionblock_title"] = "";
2573  $all_questions[$question_id]["questionblock_id"] = "";
2574  $all_questions[$question_id]["questionblock_show_questiontext"] = 1;
2575  $all_questions[$question_id]["questionblock_show_blocktitle"] = 1;
2576  $currentblock = "";
2577  $constraints = $this->getConstraints($question_id);
2578  $all_questions[$question_id]["constraints"] = $constraints;
2579  }
2580  if (!isset($all_pages[$pageindex]))
2581  {
2582  $all_pages[$pageindex] = array();
2583  }
2584  array_push($all_pages[$pageindex], $all_questions[$question_id]);
2585  }
2586  // calculate position percentage for every page
2587  $max = count($all_pages);
2588  $counter = 1;
2589  foreach ($all_pages as $index => $block)
2590  {
2591  foreach ($block as $blockindex => $question)
2592  {
2593  $all_pages[$index][$blockindex]["position"] = $counter / $max;
2594  }
2595  $counter++;
2596  }
2597  return $all_pages;
2598  }
2599 
2608  function getNextPage($active_page_question_id, $direction)
2609  {
2610  $foundpage = -1;
2611  $pages =& $this->getSurveyPages();
2612  if (strcmp($active_page_question_id, "") == 0)
2613  {
2614  return $pages[0];
2615  }
2616  foreach ($pages as $key => $question_array)
2617  {
2618  foreach ($question_array as $question)
2619  {
2620  if ($active_page_question_id == $question["question_id"])
2621  {
2622  $foundpage = $key;
2623  }
2624  }
2625  }
2626  if ($foundpage == -1)
2627  {
2628  // error: page not found
2629  }
2630  else
2631  {
2632  $foundpage += $direction;
2633  if ($foundpage < 0)
2634  {
2635  return 0;
2636  }
2637  if ($foundpage >= count($pages))
2638  {
2639  return 1;
2640  }
2641  return $pages[$foundpage];
2642  }
2643  }
2644 
2651  function &getAvailableQuestionpools($use_obj_id = false, $could_be_offline = false, $showPath = FALSE, $permission = "read")
2652  {
2653  include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php";
2654  return ilObjSurveyQuestionPool::_getAvailableQuestionpools($use_obj_id, $could_be_offline, $showPath, $permission);
2655  }
2656 
2663  {
2664  global $ilDB;
2665 
2666  $result_array = array();
2667  $result = $ilDB->queryF("SELECT svy_constraint.*, svy_relation.*, svy_qst_constraint.question_fi ref_question_fi FROM svy_qst_constraint, svy_constraint, ".
2668  "svy_relation WHERE svy_constraint.relation_fi = svy_relation.relation_id AND ".
2669  "svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_constraint.constraint_id = %s",
2670  array('integer'),
2671  array($id)
2672  );
2673  $pc = array();
2674  if ($result->numRows())
2675  {
2676  $pc = $ilDB->fetchAssoc($result);
2677  }
2678  return $pc;
2679  }
2680 
2686  function getConstraints($question_id)
2687  {
2688  global $ilDB;
2689 
2690  $result_array = array();
2691  $result = $ilDB->queryF("SELECT svy_constraint.*, svy_relation.* FROM svy_qst_constraint, svy_constraint, svy_relation ".
2692  "WHERE svy_constraint.relation_fi = svy_relation.relation_id AND ".
2693  "svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_qst_constraint.question_fi = %s ".
2694  "AND svy_qst_constraint.survey_fi = %s",
2695  array('integer','integer'),
2696  array($question_id, $this->getSurveyId())
2697  );
2698  while ($row = $ilDB->fetchAssoc($result))
2699  {
2700  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
2701  $question_type = SurveyQuestion::_getQuestionType($row["question_fi"]);
2702  SurveyQuestion::_includeClass($question_type);
2703  $question = new $question_type();
2704  $question->loadFromDb($row["question_fi"]);
2705  $valueoutput = $question->getPreconditionValueOutput($row["value"]);
2706  array_push($result_array, array("id" => $row["constraint_id"], "question" => $row["question_fi"], "short" => $row["shortname"], "long" => $row["longname"], "value" => $row["value"], "conjunction" => $row["conjunction"], "valueoutput" => $valueoutput));
2707  }
2708  return $result_array;
2709  }
2710 
2716  function _getConstraints($survey_id)
2717  {
2718  global $ilDB;
2719  $result_array = array();
2720  $result = $ilDB->queryF("SELECT svy_qst_constraint.question_fi as for_question, svy_constraint.*, svy_relation.* ".
2721  "FROM svy_qst_constraint, svy_constraint, svy_relation WHERE svy_constraint.relation_fi = svy_relation.relation_id ".
2722  "AND svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_qst_constraint.survey_fi = %s",
2723  array('integer'),
2724  array($survey_id)
2725  );
2726  while ($row = $ilDB->fetchAssoc($result))
2727  {
2728  array_push($result_array, array("id" => $row["constraint_id"], "for_question" => $row["for_question"], "question" => $row["question_fi"], "short" => $row["shortname"], "long" => $row["longname"], "relation_id" => $row["relation_id"], "value" => $row["value"], 'conjunction' => $row['conjunction']));
2729  }
2730  return $result_array;
2731  }
2732 
2733 
2739  function &getVariables($question_id)
2740  {
2741  global $ilDB;
2742 
2743  $result_array = array();
2744  $result = $ilDB->queryF("SELECT svy_variable.*, svy_category.title FROM svy_variable LEFT JOIN ".
2745  "svy_category ON svy_variable.category_fi = svy_category.category_id WHERE svy_variable.question_fi = %s ".
2746  "ORDER BY svy_variable.sequence",
2747  array('integer'),
2748  array($question_id)
2749  );
2750  while ($row = $ilDB->fetchObject($result))
2751  {
2752  $result_array[$row->sequence] = $row;
2753  }
2754  return $result_array;
2755  }
2756 
2765  function addConstraint($if_question_id, $relation, $value, $conjunction)
2766  {
2767  global $ilDB;
2768 
2769  $next_id = $ilDB->nextId('svy_constraint');
2770  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_constraint (constraint_id, question_fi, relation_fi, value, conjunction) VALUES ".
2771  "(%s, %s, %s, %s, %s)",
2772  array('integer','integer','integer','float', 'integer'),
2773  array($next_id, $if_question_id, $relation, $value, $conjunction)
2774  );
2775  if ($affectedRows)
2776  {
2777  return $next_id;
2778  }
2779  else
2780  {
2781  return null;
2782  }
2783  }
2784 
2785 
2792  public function addConstraintToQuestion($to_question_id, $constraint_id)
2793  {
2794  global $ilDB;
2795 
2796  $next_id = $ilDB->nextId('svy_qst_constraint');
2797  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qst_constraint (question_constraint_id, survey_fi, question_fi, ".
2798  "constraint_fi) VALUES (%s, %s, %s, %s)",
2799  array('integer','integer','integer','integer'),
2800  array($next_id, $this->getSurveyId(), $to_question_id, $constraint_id)
2801  );
2802  }
2803 
2814  function updateConstraint($precondition_id, $if_question_id, $relation, $value, $conjunction)
2815  {
2816  global $ilDB;
2817  $affectedRows = $ilDB->manipulateF("UPDATE svy_constraint SET question_fi = %s, relation_fi = %s, value = %s, conjunction = %s ".
2818  "WHERE constraint_id = %s",
2819  array('integer','integer','float','integer','integer'),
2820  array($if_question_id, $relation, $value, $conjunction, $precondition_id)
2821  );
2822  }
2823 
2824  public function updateConjunctionForQuestions($questions, $conjunction)
2825  {
2826  global $ilDB;
2827  foreach ($questions as $question_id)
2828  {
2829  $affectedRows = $ilDB->manipulateF("UPDATE svy_constraint SET conjunction = %s ".
2830  "WHERE constraint_id IN (SELECT constraint_fi FROM svy_qst_constraint WHERE svy_qst_constraint.question_fi = %s)",
2831  array('integer','integer'),
2832  array($conjunction, $question_id)
2833  );
2834  }
2835  }
2836 
2842  function getAllRelations($short_as_key = false)
2843  {
2844  global $ilDB;
2845 
2846  // #7987
2847  $custom_order = array("equal", "not_equal", "less", "less_or_equal", "more", "more_or_equal");
2848  $custom_order = array_flip($custom_order);
2849 
2850  $result_array = array();
2851  $result = $ilDB->query("SELECT * FROM svy_relation");
2852  while ($row = $ilDB->fetchAssoc($result))
2853  {
2854  if ($short_as_key)
2855  {
2856  $result_array[$row["shortname"]] = array("short" => $row["shortname"], "long" => $row["longname"], "id" => $row["relation_id"], "order" => $custom_order[$row["longname"]]);
2857  }
2858  else
2859  {
2860  $result_array[$row["relation_id"]] = array("short" => $row["shortname"], "long" => $row["longname"], "order" => $custom_order[$row["longname"]]);
2861  }
2862  }
2863 
2864  $result_array = ilUtil::sortArray($result_array, "order", "ASC", true, true);
2865  foreach($result_array as $idx => $item)
2866  {
2867  unset($result_array[$idx]["order"]);
2868  }
2869 
2870  return $result_array;
2871  }
2872 
2876  public function disinviteAllUsers()
2877  {
2878  global $ilDB;
2879  $result = $ilDB->queryF("SELECT user_fi FROM svy_inv_usr WHERE survey_fi = %s",
2880  array('integer'),
2881  array($this->getSurveyId())
2882  );
2883  while ($row = $ilDB->fetchAssoc($result))
2884  {
2885  $this->disinviteUser($row['user_fi']);
2886  }
2887  }
2888 
2894  public function disinviteUser($user_id)
2895  {
2896  global $ilDB;
2897 
2898  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_inv_usr WHERE survey_fi = %s AND user_fi = %s",
2899  array('integer','integer'),
2900  array($this->getSurveyId(), $user_id)
2901  );
2902  include_once './Services/User/classes/class.ilObjUser.php';
2903  ilObjUser::_dropDesktopItem($user_id, $this->getRefId(), "svy");
2904  }
2905 
2912  function inviteUser($user_id)
2913  {
2914  global $ilDB;
2915 
2916  $result = $ilDB->queryF("SELECT user_fi FROM svy_inv_usr WHERE user_fi = %s AND survey_fi = %s",
2917  array('integer','integer'),
2918  array($user_id, $this->getSurveyId())
2919  );
2920  if ($result->numRows() < 1)
2921  {
2922  $next_id = $ilDB->nextId('svy_inv_usr');
2923  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_inv_usr (invited_user_id, survey_fi, user_fi, tstamp) " .
2924  "VALUES (%s, %s, %s, %s)",
2925  array('integer','integer','integer','integer'),
2926  array($next_id, $this->getSurveyId(), $user_id, time())
2927  );
2928  }
2929  if ($this->getInvitation() == self::INVITATION_ON)
2930  {
2931  include_once './Services/User/classes/class.ilObjUser.php';
2932  ilObjUser::_addDesktopItem($user_id, $this->getRefId(), "svy");
2933  }
2934  }
2935 
2942  function inviteGroup($group_id)
2943  {
2944  global $ilAccess;
2945  $invited = 0;
2946  include_once "./Modules/Group/classes/class.ilObjGroup.php";
2947  $group = new ilObjGroup($group_id);
2948  $members = $group->getGroupMemberIds();
2949  foreach ($members as $user_id)
2950  {
2951  if ($ilAccess->checkAccessOfUser($user_id, "read", "", $this->getRefId(), "svy", $this->getId()))
2952  {
2953  $this->inviteUser($user_id);
2954  if ($this->getInvitation() == self::INVITATION_ON)
2955  {
2956  include_once './Services/User/classes/class.ilObjUser.php';
2957  ilObjUser::_addDesktopItem($user_id, $this->getRefId(), "svy");
2958  }
2959  }
2960  }
2961  return $invited;
2962  }
2963 
2970  function inviteRole($role_id)
2971  {
2972  global $rbacreview;
2973  global $ilAccess;
2974  $invited = 0;
2975  $members = $rbacreview->assignedUsers($role_id);
2976  foreach ($members as $user_id)
2977  {
2978  if ($ilAccess->checkAccessOfUser($user_id, "read", "", $this->getRefId(), "svy", $this->getId()))
2979  {
2980  $this->inviteUser($user_id);
2981  if ($this->getInvitation() == self::INVITATION_ON)
2982  {
2983  include_once './Services/User/classes/class.ilObjUser.php';
2984  ilObjUser::_addDesktopItem($user_id, $this->getRefId(), "svy");
2985  }
2986  }
2987  }
2988  return $invited;
2989  }
2990 
2997  function &getInvitedUsers()
2998  {
2999  global $ilDB;
3000 
3001  $result_array = array();
3002  $result = $ilDB->queryF("SELECT user_fi FROM svy_inv_usr WHERE survey_fi = %s",
3003  array('integer'),
3004  array($this->getSurveyId())
3005  );
3006  while ($row = $ilDB->fetchAssoc($result))
3007  {
3008  array_push($result_array, $row["user_fi"]);
3009  }
3010  return $result_array;
3011  }
3012 
3020  function deleteWorkingData($question_id, $active_id)
3021  {
3022  global $ilDB;
3023 
3024  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE question_fi = %s AND active_fi = %s",
3025  array('integer','integer'),
3026  array($question_id, $active_id)
3027  );
3028  }
3029 
3038  function loadWorkingData($question_id, $active_id)
3039  {
3040  global $ilDB;
3041  $result_array = array();
3042  $result = $ilDB->queryF("SELECT * FROM svy_answer WHERE question_fi = %s AND active_fi = %s",
3043  array('integer','integer'),
3044  array($question_id, $active_id)
3045  );
3046  if ($result->numRows() >= 1)
3047  {
3048  while ($row = $ilDB->fetchAssoc($result))
3049  {
3050  array_push($result_array, $row);
3051  }
3052  return $result_array;
3053  }
3054  else
3055  {
3056  return $result_array;
3057  }
3058  }
3059 
3066  function fillSurveyForUser($user_id = ANONYMOUS_USER_ID)
3067  {
3068  global $ilDB;
3069  // create an anonymous key
3070  $anonymous_id = $this->createNewAccessCode();
3071  $this->saveUserAccessCode($user_id, $anonymous_id);
3072  // create the survey_finished dataset and set the survey finished already
3073  $active_id = $ilDB->nextId('svy_finished');
3074  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_finished (finished_id, survey_fi, user_fi, anonymous_id, state, tstamp) ".
3075  "VALUES (%s, %s, %s, %s, %s, %s)",
3076  array('integer','integer','integer','text','text','integer'),
3077  array($active_id, $this->getSurveyId(), $user_id, $anonymous_id, 1, time())
3078  );
3079  // fill the questions randomly
3080  $pages =& $this->getSurveyPages();
3081  foreach ($pages as $key => $question_array)
3082  {
3083  foreach ($question_array as $question)
3084  {
3085  // instanciate question
3086  require_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
3087  $question =& SurveyQuestion::_instanciateQuestion($question["question_id"]);
3088  $question->saveRandomData($active_id);
3089  }
3090  }
3091  }
3092 
3099  function startSurvey($user_id, $anonymous_id, $appraisee_id)
3100  {
3101  global $ilDB;
3102 
3103  if ($this->getAnonymize() && (strlen($anonymous_id) == 0)) return;
3104 
3105  if (strcmp($user_id, "") == 0)
3106  {
3107  if ($user_id == ANONYMOUS_USER_ID)
3108  {
3109  $user_id = 0;
3110  }
3111  }
3112  $next_id = $ilDB->nextId('svy_finished');
3113  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_finished (finished_id, survey_fi, user_fi, anonymous_id, state, tstamp, appr_id) ".
3114  "VALUES (%s, %s, %s, %s, %s, %s, %s)",
3115  array('integer','integer','integer','text','text','integer','integer'),
3116  array($next_id, $this->getSurveyId(), $user_id, $anonymous_id, 0, time(), $appraisee_id)
3117  );
3118  return $next_id;
3119  }
3120 
3127  function finishSurvey($finished_id)
3128  {
3129  global $ilDB;
3130 
3131  $ilDB->manipulateF("UPDATE svy_finished SET state = %s, tstamp = %s".
3132  " WHERE survey_fi = %s AND finished_id = %s",
3133  array('text','integer','integer','integer'),
3134  array(1, time(), $this->getSurveyId(), $finished_id)
3135  );
3136 
3137  $this->checkTutorNotification();
3138  }
3139 
3147  function setPage($finished_id, $page_id)
3148  {
3149  global $ilDB;
3150 
3151  $affectedRows = $ilDB->manipulateF("UPDATE svy_finished SET lastpage = %s WHERE finished_id = %s",
3152  array('integer','integer'),
3153  array(($page_id) ? $page_id : 0, $finished_id)
3154  );
3155  }
3156 
3157  function sendNotificationMail($user_id, $anonymize_id, $appr_id)
3158  {
3159  include_once "./Services/User/classes/class.ilObjUser.php";
3160  include_once "./Services/User/classes/class.ilUserUtil.php";
3161 
3162  // #12755
3163  $placeholders = array(
3164  "FIRST_NAME" => "firstname",
3165  "LAST_NAME" => "lastname",
3166  "LOGIN" => "login",
3167  // old style
3168  "firstname" => "firstname"
3169  );
3170 
3171  $recipients = preg_split('/,/', $this->mailaddresses);
3172  foreach ($recipients as $recipient)
3173  {
3174  // #11298
3175  include_once "./Services/Notification/classes/class.ilSystemNotification.php";
3176  $ntf = new ilSystemNotification();
3177  $ntf->setLangModules(array("survey"));
3178  $ntf->setRefId($this->getRefId());
3179  $ntf->setSubjectLangId('finished_mail_subject');
3180 
3181  $messagetext = $this->mailparticipantdata;
3182  if(trim($messagetext))
3183  {
3184  if (!$this->hasAnonymizedResults())
3185  {
3186  $data = ilObjUser::_getUserData(array($user_id));
3187  $data = $data[0];
3188  }
3189  foreach ($placeholders as $key => $mapping)
3190  {
3191  if ($this->hasAnonymizedResults()) // #16480
3192  {
3193  $messagetext = str_replace('[' . $key . ']', '', $messagetext);
3194  }
3195  else
3196  {
3197  $messagetext = str_replace('[' . $key . ']', trim($data[$mapping]), $messagetext);
3198  }
3199  }
3200  $ntf->setIntroductionDirect($messagetext);
3201  }
3202  else
3203  {
3204  $ntf->setIntroductionLangId('survey_notification_finished_introduction');
3205  }
3206 
3207  // 360°? add appraisee data
3208  if($appr_id)
3209  {
3210  $ntf->addAdditionalInfo('survey_360_appraisee',
3212  }
3213 
3214  $active_id = $this->getActiveID($user_id, $anonymize_id, $appr_id);
3215  $ntf->addAdditionalInfo('results',
3216  $this->getParticipantTextResults($active_id), true);
3217 
3218  $ntf->setGotoLangId('survey_notification_tutor_link');
3219  $ntf->setReasonLangId('survey_notification_finished_reason');
3220 
3221  $ntf->sendMail(array($recipient), null, null);
3222  }
3223  }
3224 
3225  protected function getParticipantTextResults($active_id)
3226  {
3227  $textresult = "";
3228  $userResults =& $this->getUserSpecificResults(array($active_id));
3229  $questions =& $this->getSurveyQuestions(true);
3230  $questioncounter = 1;
3231  foreach ($questions as $question_id => $question_data)
3232  {
3233  $textresult .= $questioncounter++ . ". " . $question_data["title"] . "\n";
3234  $found = $userResults[$question_id][$active_id];
3235  $text = "";
3236  if (is_array($found))
3237  {
3238  $text = implode("\n", $found);
3239  }
3240  else
3241  {
3242  $text = $found;
3243  }
3244  if (strlen($text) == 0) $text = self::getSurveySkippedValue();
3245  $text = str_replace("<br />", "\n", $text);
3246  $textresult .= $text . "\n\n";
3247  }
3248  return $textresult;
3249  }
3250 
3252  {
3253  $counter = 0;
3254  $questions =& $this->getSurveyQuestions();
3255  $counter++;
3256  foreach ($questions as $data)
3257  {
3258  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
3259  $question = SurveyQuestion::_instanciateQuestion($data["question_id"]);
3260 
3261  $eval = $this->getCumulatedResults($question);
3262  }
3263  }
3264 
3272  function isAllowedToTakeMultipleSurveys($userid = "")
3273  {
3274  // #7927: special users are deprecated
3275  return false;
3276 
3277  /*
3278  $result = FALSE;
3279  if ($this->getAnonymize())
3280  {
3281  if ($this->isAccessibleWithoutCode())
3282  {
3283  if (strlen($username) == 0)
3284  {
3285  global $ilUser;
3286  $userid = $ilUser->getId();
3287  }
3288  global $ilSetting;
3289  $surveysetting = new ilSetting("survey");
3290  $allowedUsers = strlen($surveysetting->get("multiple_survey_users")) ? explode(",",$surveysetting->get("multiple_survey_users")) : array();
3291  if (in_array($userid, $allowedUsers))
3292  {
3293  $result = TRUE;
3294  }
3295  }
3296  }
3297  return $result;
3298  */
3299  }
3300 
3308  function isSurveyStarted($user_id, $anonymize_id, $appr_id = 0)
3309  {
3310  global $ilDB;
3311 
3312  // #15031 - should not matter if code was used by registered or anonymous (each code must be unique)
3313  if($anonymize_id)
3314  {
3315  $result = $ilDB->queryF("SELECT * FROM svy_finished".
3316  " WHERE survey_fi = %s AND anonymous_id = %s AND appr_id = %s",
3317  array('integer','text','integer'),
3318  array($this->getSurveyId(), $anonymize_id, $appr_id)
3319  );
3320  }
3321  else
3322  {
3323  $result = $ilDB->queryF("SELECT * FROM svy_finished".
3324  " WHERE survey_fi = %s AND user_fi = %s AND appr_id = %s",
3325  array('integer','integer','integer'),
3326  array($this->getSurveyId(), $user_id, $appr_id)
3327  );
3328  }
3329  if ($result->numRows() == 0)
3330  {
3331  return false;
3332  }
3333  else
3334  {
3335  $row = $ilDB->fetchAssoc($result);
3336 
3337  // yes, we are doing it this way
3338  $_SESSION["finished_id"][$this->getId()] = $row["finished_id"];
3339 
3340  return (int)$row["state"];
3341  }
3342 
3343  /*
3344  if ($this->getAnonymize())
3345  {
3346  if ((($user_id != ANONYMOUS_USER_ID) && sizeof($anonymize_id)) && (!($this->isAccessibleWithoutCode() && $this->isAllowedToTakeMultipleSurveys())))
3347  {
3348  $result = $ilDB->queryF("SELECT * FROM svy_finished".
3349  " WHERE survey_fi = %s AND user_fi = %s AND appr_id = %s",
3350  array('integer','integer','integer'),
3351  array($this->getSurveyId(), $user_id, $appr_id)
3352  );
3353  }
3354  else
3355  {
3356  $result = $ilDB->queryF("SELECT * FROM svy_finished".
3357  " WHERE survey_fi = %s AND anonymous_id = %s AND appr_id = %s",
3358  array('integer','text','integer'),
3359  array($this->getSurveyId(), $anonymize_id, $appr_id)
3360  );
3361  }
3362  }
3363  else
3364  {
3365  $result = $ilDB->queryF("SELECT * FROM svy_finished".
3366  " WHERE survey_fi = %s AND user_fi = %s AND appr_id = %s",
3367  array('integer','integer','integer'),
3368  array($this->getSurveyId(), $user_id, $appr_id)
3369  );
3370  }
3371  if ($result->numRows() == 0)
3372  {
3373  return false;
3374  }
3375  else
3376  {
3377  $row = $ilDB->fetchAssoc($result);
3378  $_SESSION["finished_id"][$this->getId()] = $row["finished_id"];
3379  return (int)$row["state"];
3380  }
3381  */
3382  }
3383 
3391  function getActiveID($user_id, $anonymize_id, $appr_id)
3392  {
3393  global $ilDB;
3394 
3395  // see self::isSurveyStarted()
3396 
3397  // #15031 - should not matter if code was used by registered or anonymous (each code must be unique)
3398  if($anonymize_id)
3399  {
3400  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished".
3401  " WHERE survey_fi = %s AND anonymous_id = %s AND appr_id = %s",
3402  array('integer','text','integer'),
3403  array($this->getSurveyId(), $anonymize_id, $appr_id)
3404  );
3405  }
3406  else
3407  {
3408  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished".
3409  " WHERE survey_fi = %s AND user_fi = %s AND appr_id = %s",
3410  array('integer','integer','integer'),
3411  array($this->getSurveyId(), $user_id, $appr_id)
3412  );
3413  }
3414  if ($result->numRows() == 0)
3415  {
3416  return false;
3417  }
3418  else
3419  {
3420  $row = $ilDB->fetchAssoc($result);
3421  return $row["finished_id"];
3422  }
3423 
3424  /*
3425  if ($this->getAnonymize())
3426  {
3427  if ((($user_id != ANONYMOUS_USER_ID) && (strlen($anonymize_id) == 0)) && (!($this->isAccessibleWithoutCode() && $this->isAllowedToTakeMultipleSurveys())))
3428  {
3429  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished".
3430  " WHERE survey_fi = %s AND user_fi = %s AND appr_id = %s",
3431  array('integer','integer','integer'),
3432  array($this->getSurveyId(), $user_id, $appr_id)
3433  );
3434  }
3435  else
3436  {
3437  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished".
3438  " WHERE survey_fi = %s AND anonymous_id = %s AND appr_id = %s",
3439  array('integer','text','integer'),
3440  array($this->getSurveyId(), $anonymize_id, $appr_id)
3441  );
3442  }
3443  }
3444  else
3445  {
3446  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished".
3447  " WHERE survey_fi = %s AND user_fi = %s AND appr_id = %s",
3448  array('integer','integer','integer'),
3449  array($this->getSurveyId(), $user_id, $appr_id)
3450  );
3451  }
3452  if ($result->numRows() == 0)
3453  {
3454  return false;
3455  }
3456  else
3457  {
3458  $row = $ilDB->fetchAssoc($result);
3459  return $row["finished_id"];
3460  }
3461  */
3462  }
3463 
3471  function getLastActivePage($active_id)
3472  {
3473  global $ilDB;
3474  $result = $ilDB->queryF("SELECT lastpage FROM svy_finished WHERE finished_id = %s",
3475  array('integer'),
3476  array($active_id)
3477  );
3478  if ($result->numRows() == 0)
3479  {
3480  return "";
3481  }
3482  else
3483  {
3484  $row = $ilDB->fetchAssoc($result);
3485  return ($row["lastpage"]) ? $row["lastpage"] : '';
3486  }
3487  }
3488 
3497  function checkConstraint($constraint_data, $working_data)
3498  {
3499  if (count($working_data) == 0)
3500  {
3501  return 0;
3502  }
3503 
3504  if ((count($working_data) == 1) and (strcmp($working_data[0]["value"], "") == 0))
3505  {
3506  return 0;
3507  }
3508 
3509  $found = false;
3510  foreach ($working_data as $data)
3511  {
3512  switch ($constraint_data["short"])
3513  {
3514  case "<":
3515  if ($data["value"] < $constraint_data["value"])
3516  {
3517  $found = true;
3518  }
3519  break;
3520 
3521  case "<=":
3522  if ($data["value"] <= $constraint_data["value"])
3523  {
3524  $found = true;
3525  }
3526  break;
3527 
3528  case "=":
3529  if ($data["value"] == $constraint_data["value"])
3530  {
3531  $found = true;
3532  }
3533  break;
3534 
3535  case "<>":
3536  if ($data["value"] <> $constraint_data["value"])
3537  {
3538  $found = true;
3539  }
3540  break;
3541 
3542  case ">=":
3543  if ($data["value"] >= $constraint_data["value"])
3544  {
3545  $found = true;
3546  }
3547  break;
3548 
3549  case ">":
3550  if ($data["value"] > $constraint_data["value"])
3551  {
3552  $found = true;
3553  }
3554  break;
3555  }
3556  if ($found)
3557  {
3558  break;
3559  }
3560  }
3561 
3562  return (int)$found;
3563  }
3564 
3565  function _hasDatasets($survey_id)
3566  {
3567  global $ilDB;
3568 
3569  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
3570  array('integer'),
3571  array($survey_id)
3572  );
3573  return ($result->numRows()) ? true : false;
3574  }
3575 
3583  {
3584  global $ilDB, $ilLog;
3585 
3586  $users = array();
3587  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s",
3588  array('integer'),
3589  array($this->getSurveyId())
3590  );
3591  if ($result->numRows())
3592  {
3593  while ($row = $ilDB->fetchAssoc($result))
3594  {
3595  array_push($users, $row["finished_id"]);
3596  }
3597  }
3598  return $users;
3599  }
3600 
3607  function &getUserSpecificResults($finished_ids)
3608  {
3609  global $ilDB;
3610 
3611  $evaluation = array();
3612  $questions =& $this->getSurveyQuestions();
3613  foreach ($questions as $question_id => $question_data)
3614  {
3615  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
3616  $question_type = SurveyQuestion::_getQuestionType($question_id);
3617  SurveyQuestion::_includeClass($question_type);
3618  $question = new $question_type();
3619  $question->loadFromDb($question_id);
3620  $data =& $question->getUserAnswers($this->getSurveyId(), $finished_ids);
3621  $evaluation[$question_id] = $data;
3622  }
3623  return $evaluation;
3624  }
3625 
3633  function getUserDataFromActiveId($active_id)
3634  {
3635  global $ilDB;
3636 
3637  $surveySetting = new ilSetting("survey");
3638  $use_anonymous_id = array_key_exists("use_anonymous_id", $_GET) ? $_GET["use_anonymous_id"] : $surveySetting->get("use_anonymous_id");
3639  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE finished_id = %s",
3640  array('integer'),
3641  array($active_id)
3642  );
3643  $row = array();
3644  $foundrows = $result->numRows();
3645  if ($foundrows)
3646  {
3647  $row = $ilDB->fetchAssoc($result);
3648  }
3649  $name = ($use_anonymous_id) ? $row["anonymous_id"] : $this->lng->txt("anonymous");
3650  $userdata = array(
3651  "fullname" => $name,
3652  "sortname" => $name,
3653  "firstname" => "",
3654  "lastname" => "",
3655  "login" => "",
3656  "gender" => "",
3657  "active_id" => "$active_id"
3658  );
3659  if ($foundrows)
3660  {
3661  if (($row["user_fi"] > 0) && ($row["user_fi"] != ANONYMOUS_USER_ID) &&
3662  !$this->hasAnonymizedResults() &&
3663  !$this->get360Mode()) // 360° uses ANONYMIZE_CODE_ALL which is wrong - see ilObjSurveyGUI::afterSave()
3664  {
3665  include_once './Services/User/classes/class.ilObjUser.php';
3666  if (strlen(ilObjUser::_lookupLogin($row["user_fi"])) == 0)
3667  {
3668  $userdata["fullname"] = $userdata["sortname"] = $this->lng->txt("deleted_user");
3669  }
3670  else
3671  {
3672  $user = new ilObjUser($row["user_fi"]);
3673  $userdata["fullname"] = $user->getFullname();
3674  $gender = $user->getGender();
3675  if (strlen($gender) == 1) $gender = $this->lng->txt("gender_$gender");
3676  $userdata["gender"] = $gender;
3677  $userdata["firstname"] = $user->getFirstname();
3678  $userdata["lastname"] = $user->getLastname();
3679  $userdata["sortname"] = $user->getLastname() . ", " . $user->getFirstname();
3680  $userdata["login"] = $user->getLogin();
3681  }
3682  }
3683  }
3684  return $userdata;
3685  }
3686 
3696  function &getEvaluationByUser($questions, $active_id)
3697  {
3698  global $ilDB;
3699 
3700  // collect all answers
3701  $answers = array();
3702  $result = $ilDB->queryF("SELECT * FROM svy_answer WHERE active_fi = %s",
3703  array('integer'),
3704  array($active_id)
3705  );
3706  while ($row = $ilDB->fetchAssoc($result))
3707  {
3708  if (!is_array($answers[$row["question_fi"]]))
3709  {
3710  $answers[$row["question_fi"]] = array();
3711  }
3712  array_push($answers[$row["question_fi"]], $row);
3713  }
3714  $userdata = $this->getUserDataFromActiveId($active_id);
3715  $resultset = array(
3716  "name" => $userdata["fullname"],
3717  "firstname" => $userdata["firstname"],
3718  "lastname" => $userdata["lastname"],
3719  "login" => $userdata["login"],
3720  "gender" => $userdata["gender"],
3721  "answers" => array()
3722  );
3723  foreach ($questions as $key => $question)
3724  {
3725  if (array_key_exists($key, $answers))
3726  {
3727  $resultset["answers"][$key] = $answers[$key];
3728  }
3729  else
3730  {
3731  $resultset["answers"][$key] = array();
3732  }
3733  sort($resultset["answers"][$key]);
3734  }
3735  return $resultset;
3736  }
3737 
3746  function getCumulatedResults(&$question, $finished_ids)
3747  {
3748  global $ilDB;
3749 
3750  if(!$finished_ids)
3751  {
3752  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
3753  array('integer'),
3754  array($this->getSurveyId())
3755  );
3756  $nr_of_users = $result->numRows();
3757  }
3758  else
3759  {
3760  $nr_of_users = sizeof($finished_ids);
3761  }
3762 
3763  $result_array =& $question->getCumulatedResults($this->getSurveyId(), $nr_of_users, $finished_ids);
3764  return $result_array;
3765  }
3766 
3774  function _getNrOfParticipants($survey_id)
3775  {
3776  global $ilDB;
3777 
3778  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
3779  array('integer'),
3780  array($survey_id)
3781  );
3782  return $result->numRows();
3783  }
3784 
3785  function &getQuestions($question_ids)
3786  {
3787  global $ilDB;
3788 
3789  $result_array = array();
3790  $result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag FROM svy_question, svy_qtype WHERE ".
3791  "svy_question.questiontype_fi = svy_qtype.questiontype_id AND svy_question.tstamp > 0 AND ".
3792  $ilDB->in('svy_question.question_id', $question_ids, false, 'integer'));
3793  while ($row = $ilDB->fetchAssoc($result))
3794  {
3795  array_push($result_array, $row);
3796  }
3797  return $result_array;
3798  }
3799 
3805  function getQuestionsTable($arrFilter)
3806  {
3807  global $ilUser;
3808  global $ilDB;
3809  $where = "";
3810  if (is_array($arrFilter))
3811  {
3812  if (array_key_exists('title', $arrFilter) && strlen($arrFilter['title']))
3813  {
3814  $where .= " AND " . $ilDB->like('svy_question.title', 'text', "%%" . $arrFilter['title'] . "%%");
3815  }
3816  if (array_key_exists('description', $arrFilter) && strlen($arrFilter['description']))
3817  {
3818  $where .= " AND " . $ilDB->like('svy_question.description', 'text', "%%" . $arrFilter['description'] . "%%");
3819  }
3820  if (array_key_exists('author', $arrFilter) && strlen($arrFilter['author']))
3821  {
3822  $where .= " AND " . $ilDB->like('svy_question.author', 'text', "%%" . $arrFilter['author'] . "%%");
3823  }
3824  if (array_key_exists('type', $arrFilter) && strlen($arrFilter['type']))
3825  {
3826  $where .= " AND svy_qtype.type_tag = " . $ilDB->quote($arrFilter['type'], 'text');
3827  }
3828  if (array_key_exists('spl', $arrFilter) && strlen($arrFilter['spl']))
3829  {
3830  $where .= " AND svy_question.obj_fi = " . $ilDB->quote($arrFilter['spl'], 'integer');
3831  }
3832  }
3833 
3834  $spls =& $this->getAvailableQuestionpools($use_obj_id = TRUE, $could_be_offline = FALSE, $showPath = FALSE);
3835  $forbidden = "";
3836  $forbidden = " AND " . $ilDB->in('svy_question.obj_fi', array_keys($spls), false, 'integer');
3837  $forbidden .= " AND svy_question.complete = " . $ilDB->quote("1", 'text');
3838  $existing = "";
3839  $existing_questions =& $this->getExistingQuestions();
3840  if (count($existing_questions))
3841  {
3842  $existing = " AND " . $ilDB->in('svy_question.question_id', $existing_questions, true, 'integer');
3843  }
3844 
3845  include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php";
3847 
3848  $query_result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag, svy_qtype.plugin, object_reference.ref_id".
3849  " FROM svy_question, svy_qtype, object_reference".
3850  " WHERE svy_question.original_id IS NULL".$forbidden.$existing.
3851  " AND svy_question.obj_fi = object_reference.obj_id AND svy_question.tstamp > 0".
3852  " AND svy_question.questiontype_fi = svy_qtype.questiontype_id " . $where);
3853 
3854  $rows = array();
3855  if ($query_result->numRows())
3856  {
3857  while ($row = $ilDB->fetchAssoc($query_result))
3858  {
3859  if (array_key_exists('spl_txt', $arrFilter) && strlen($arrFilter['spl_txt']))
3860  {
3861  if(!stristr($spls[$row["obj_fi"]], $arrFilter['spl_txt']))
3862  {
3863  continue;
3864  }
3865  }
3866 
3867  $row['ttype'] = $trans[$row['type_tag']];
3868  if ($row["plugin"])
3869  {
3870  if ($this->isPluginActive($row["type_tag"]))
3871  {
3872  array_push($rows, $row);
3873  }
3874  }
3875  else
3876  {
3877  array_push($rows, $row);
3878  }
3879  }
3880  }
3881  return $rows;
3882  }
3883 
3889  function getQuestionblocksTable($arrFilter)
3890  {
3891  global $ilUser, $ilDB;
3892 
3893  $where = "";
3894  if (is_array($arrFilter))
3895  {
3896  if (array_key_exists('title', $arrFilter) && strlen($arrFilter['title']))
3897  {
3898  $where .= " AND " . $ilDB->like('svy_qblk.title', 'text', "%%" . $arrFilter['title'] . "%%");
3899  }
3900  }
3901 
3902  $query_result = $ilDB->query("SELECT svy_qblk.*, svy_svy.obj_fi FROM svy_qblk , svy_qblk_qst, svy_svy WHERE ".
3903  "svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_svy.survey_id = svy_qblk_qst.survey_fi ".
3904  "$where GROUP BY svy_qblk.questionblock_id, svy_qblk.title, svy_qblk.show_questiontext, svy_qblk.show_blocktitle, ".
3905  "svy_qblk.owner_fi, svy_qblk.tstamp, svy_svy.obj_fi");
3906  $rows = array();
3907  if ($query_result->numRows())
3908  {
3909  $survey_ref_ids = ilUtil::_getObjectsByOperations("svy", "write");
3910  $surveytitles = array();
3911  foreach ($survey_ref_ids as $survey_ref_id)
3912  {
3913  $survey_id = ilObject::_lookupObjId($survey_ref_id);
3914  $surveytitles[$survey_id] = ilObject::_lookupTitle($survey_id);
3915  }
3916  while ($row = $ilDB->fetchAssoc($query_result))
3917  {
3918  $questions_array =& $this->getQuestionblockQuestions($row["questionblock_id"]);
3919  $counter = 1;
3920  foreach ($questions_array as $key => $value)
3921  {
3922  $questions_array[$key] = "$counter. $value";
3923  $counter++;
3924  }
3925  if (strlen($surveytitles[$row["obj_fi"]])) // only questionpools which are not in trash
3926  {
3927  $rows[$row["questionblock_id"]] = array(
3928  "questionblock_id" => $row["questionblock_id"],
3929  "title" => $row["title"],
3930  "svy" => $surveytitles[$row["obj_fi"]],
3931  "contains" => join($questions_array, ", "),
3932  "owner" => $row["owner_fi"]
3933  );
3934  }
3935  }
3936  }
3937  return $rows;
3938  }
3939 
3946  function toXML()
3947  {
3948  include_once("./Services/Xml/classes/class.ilXmlWriter.php");
3949  $a_xml_writer = new ilXmlWriter;
3950  // set xml header
3951  $a_xml_writer->xmlHeader();
3952  $attrs = array(
3953  "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
3954  "xsi:noNamespaceSchemaLocation" => "http://www.ilias.de/download/xsd/ilias_survey_4_2.xsd"
3955  );
3956  $a_xml_writer->xmlStartTag("surveyobject", $attrs);
3957  $attrs = array(
3958  "id" => $this->getSurveyId(),
3959  "title" => $this->getTitle()
3960  );
3961  $a_xml_writer->xmlStartTag("survey", $attrs);
3962 
3963  $a_xml_writer->xmlElement("description", NULL, $this->getDescription());
3964  $a_xml_writer->xmlElement("author", NULL, $this->getAuthor());
3965  $a_xml_writer->xmlStartTag("objectives");
3966  $attrs = array(
3967  "label" => "introduction"
3968  );
3969  $this->addMaterialTag($a_xml_writer, $this->getIntroduction(), TRUE, TRUE, $attrs);
3970  $attrs = array(
3971  "label" => "outro"
3972  );
3973  $this->addMaterialTag($a_xml_writer, $this->getOutro(), TRUE, TRUE, $attrs);
3974  $a_xml_writer->xmlEndTag("objectives");
3975 
3976  if ($this->getAnonymize())
3977  {
3978  $attribs = array("enabled" => "1");
3979  }
3980  else
3981  {
3982  $attribs = array("enabled" => "0");
3983  }
3984  $a_xml_writer->xmlElement("anonymisation", $attribs);
3985  $a_xml_writer->xmlStartTag("restrictions");
3986  if ($this->getAnonymize() == 2)
3987  {
3988  $attribs = array("type" => "free");
3989  }
3990  else
3991  {
3992  $attribs = array("type" => "restricted");
3993  }
3994  $a_xml_writer->xmlElement("access", $attribs);
3995  if ($this->getStartDate())
3996  {
3997  $attrs = array("type" => "date");
3998  preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getStartDate(), $matches);
3999  $a_xml_writer->xmlElement("startingtime", $attrs, sprintf("%04d-%02d-%02dT%02d:%02d:00", $matches[1], $matches[2], $matches[3], $matches[4], $matches[5], $matches[6]));
4000  }
4001  if ($this->getEndDate())
4002  {
4003  $attrs = array("type" => "date");
4004  preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getEndDate(), $matches);
4005  $a_xml_writer->xmlElement("endingtime", $attrs, sprintf("%04d-%02d-%02dT%02d:%02d:00", $matches[1], $matches[2], $matches[3], $matches[4], $matches[5], $matches[6]));
4006 
4007  }
4008  $a_xml_writer->xmlEndTag("restrictions");
4009 
4010  // constraints
4011  $pages =& $this->getSurveyPages();
4012  $hasconstraints = FALSE;
4013  foreach ($pages as $question_array)
4014  {
4015  foreach ($question_array as $question)
4016  {
4017  if (count($question["constraints"]))
4018  {
4019  $hasconstraints = TRUE;
4020  }
4021  }
4022  }
4023 
4024  if ($hasconstraints)
4025  {
4026  $a_xml_writer->xmlStartTag("constraints");
4027  foreach ($pages as $question_array)
4028  {
4029  foreach ($question_array as $question)
4030  {
4031  if (count($question["constraints"]))
4032  {
4033  // found constraints
4034  foreach ($question["constraints"] as $constraint)
4035  {
4036  $attribs = array(
4037  "sourceref" => $question["question_id"],
4038  "destref" => $constraint["question"],
4039  "relation" => $constraint["short"],
4040  "value" => $constraint["value"],
4041  "conjunction" => $constraint["conjunction"]
4042  );
4043  $a_xml_writer->xmlElement("constraint", $attribs);
4044  }
4045  }
4046  }
4047  }
4048  $a_xml_writer->xmlEndTag("constraints");
4049  }
4050 
4051  // add the rest of the preferences in qtimetadata tags, because there is no correspondent definition in QTI
4052  $a_xml_writer->xmlStartTag("metadata");
4053 
4054  $custom_properties = array();
4055  $custom_properties["evaluation_access"] = $this->getEvaluationAccess();
4056  $custom_properties["status"] = $this->getStatus();
4057  $custom_properties["display_question_titles"] = $this->getShowQuestionTitles();
4058  $custom_properties["pool_usage"] = (int)$this->getPoolUsage();
4059 
4060  $custom_properties["own_results_view"] = (int)$this->hasViewOwnResults();
4061  $custom_properties["own_results_mail"] = (int)$this->hasMailOwnResults();
4062 
4063  $custom_properties["mode_360"] = (int)$this->get360Mode();
4064  $custom_properties["mode_360_self_eval"] = (int)$this->get360SelfEvaluation();
4065  $custom_properties["mode_360_self_rate"] = (int)$this->get360SelfRaters();
4066  $custom_properties["mode_360_self_appr"] = (int)$this->get360SelfAppraisee();
4067  $custom_properties["mode_360_results"] = $this->get360Results();
4068  $custom_properties["mode_360_skill_service"] = (int)$this->get360SkillService();
4069 
4070 
4071  // :TODO: skills?
4072 
4073  // reminder/tutor notification are (currently?) not exportable
4074 
4075  foreach($custom_properties as $label => $value)
4076  {
4077  $a_xml_writer->xmlStartTag("metadatafield");
4078  $a_xml_writer->xmlElement("fieldlabel", NULL, $label);
4079  $a_xml_writer->xmlElement("fieldentry", NULL, $value);
4080  $a_xml_writer->xmlEndTag("metadatafield");
4081  }
4082 
4083  $a_xml_writer->xmlStartTag("metadatafield");
4084  $a_xml_writer->xmlElement("fieldlabel", NULL, "SCORM");
4085  include_once "./Services/MetaData/classes/class.ilMD.php";
4086  $md = new ilMD($this->getId(),0, $this->getType());
4087  $writer = new ilXmlWriter();
4088  $md->toXml($writer);
4089  $metadata = $writer->xmlDumpMem();
4090  $a_xml_writer->xmlElement("fieldentry", NULL, $metadata);
4091  $a_xml_writer->xmlEndTag("metadatafield");
4092 
4093  $a_xml_writer->xmlEndTag("metadata");
4094  $a_xml_writer->xmlEndTag("survey");
4095 
4096  $attribs = array("id" => $this->getId());
4097  $a_xml_writer->xmlStartTag("surveyquestions", $attribs);
4098  // add questionblock descriptions
4099  $obligatory_states =& $this->getObligatoryStates();
4100  foreach ($pages as $question_array)
4101  {
4102  if (count($question_array) > 1)
4103  {
4104  $attribs = array("id" => $question_array[0]["question_id"]);
4105  $attribs = array("showQuestiontext" => $question_array[0]["questionblock_show_questiontext"],
4106  "showBlocktitle" => $question_array[0]["questionblock_show_blocktitle"]);
4107  $a_xml_writer->xmlStartTag("questionblock", $attribs);
4108  if (strlen($question_array[0]["questionblock_title"]))
4109  {
4110  $a_xml_writer->xmlElement("questionblocktitle", NULL, $question_array[0]["questionblock_title"]);
4111  }
4112  }
4113  foreach ($question_array as $question)
4114  {
4115  if (strlen($question["heading"]))
4116  {
4117  $a_xml_writer->xmlElement("textblock", NULL, $question["heading"]);
4118  }
4119  $questionObject =& $this->_instanciateQuestion($question["question_id"]);
4120  if ($questionObject !== FALSE) $questionObject->insertXML($a_xml_writer, FALSE, $obligatory_states[$question["question_id"]]);
4121  }
4122  if (count($question_array) > 1)
4123  {
4124  $a_xml_writer->xmlEndTag("questionblock");
4125  }
4126  }
4127 
4128  $a_xml_writer->xmlEndTag("surveyquestions");
4129  $a_xml_writer->xmlEndTag("surveyobject");
4130  $xml = $a_xml_writer->xmlDumpMem(FALSE);
4131  return $xml;
4132  }
4133 
4141  function &_instanciateQuestion($question_id)
4142  {
4143  if ($question_id < 1) return FALSE;
4144  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
4145  $question_type = SurveyQuestion::_getQuestionType($question_id);
4146  if (strlen($question_type) == 0) return FALSE;
4147  SurveyQuestion::_includeClass($question_type);
4148  $question = new $question_type();
4149  $question->loadFromDb($question_id);
4150  return $question;
4151  }
4152 
4159  function locateImportFiles($a_dir)
4160  {
4161  if (!is_dir($a_dir) || is_int(strpos($a_dir, "..")))
4162  {
4163  return;
4164  }
4165  $importDirectory = "";
4166  $xmlFile = "";
4167 
4168  $current_dir = opendir($a_dir);
4169  $files = array();
4170  while($entryname = readdir($current_dir))
4171  {
4172  $files[] = $entryname;
4173  }
4174 
4175  foreach($files as $file)
4176  {
4177  if(is_dir($a_dir."/".$file) and ($file != "." and $file!=".."))
4178  {
4179  // found directory created by zip
4180  $importDirectory = $a_dir."/".$file;
4181  }
4182  }
4183  closedir($current_dir);
4184  if (strlen($importDirectory))
4185  {
4186  // find the xml file
4187  $current_dir = opendir($importDirectory);
4188  $files = array();
4189  while($entryname = readdir($current_dir))
4190  {
4191  $files[] = $entryname;
4192  }
4193  foreach($files as $file)
4194  {
4195  if(@is_file($importDirectory."/".$file) && ($file != "." && $file!="..") && (ereg("^[0-9]{10}_{2}[0-9]+_{2}(svy_)*[0-9]+\.[a-z]{1,3}\$", $file) || ereg("^[0-9]{10}_{2}[0-9]+_{2}(survey__)*[0-9]+\.[a-z]{1,3}\$", $file)))
4196  {
4197  // found xml file
4198  $xmlFile = $importDirectory."/".$file;
4199  }
4200  }
4201  }
4202  return array("dir" => $importDirectory, "xml" => $xmlFile);
4203  }
4204 
4213  function importObject($file_info, $svy_qpl_id)
4214  {
4215  if ($svy_qpl_id < 1) $svy_qpl_id = -1;
4216  // check if file was uploaded
4217  $source = $file_info["tmp_name"];
4218  $error = "";
4219  if (($source == 'none') || (!$source) || $file_info["error"] > UPLOAD_ERR_OK)
4220  {
4221  $error = $this->lng->txt("import_no_file_selected");
4222  }
4223  // check correct file type
4224  $isXml = FALSE;
4225  $isZip = FALSE;
4226  if ((strcmp($file_info["type"], "text/xml") == 0) || (strcmp($file_info["type"], "application/xml") == 0))
4227  {
4228  $isXml = TRUE;
4229  }
4230  // too many different mime-types, so we use the suffix
4231  $suffix = pathinfo($file_info["name"]);
4232  if (strcmp(strtolower($suffix["extension"]), "zip") == 0)
4233  {
4234  $isZip = TRUE;
4235  }
4236  if (!$isXml && !$isZip)
4237  {
4238  $error = $this->lng->txt("import_wrong_file_type");
4239  global $ilLog;
4240  $ilLog->write("Survey: Import error. Filetype was \"" . $file_info["type"] ."\"");
4241  }
4242  if (strlen($error) == 0)
4243  {
4244  // import file as a survey
4245  $import_dir = $this->getImportDirectory();
4246  $import_subdir = "";
4247  $importfile = "";
4248  include_once "./Services/Utilities/classes/class.ilUtil.php";
4249  if ($isZip)
4250  {
4251  $importfile = $import_dir."/".$file_info["name"];
4252  ilUtil::moveUploadedFile($source, $file_info["name"], $importfile);
4253  ilUtil::unzip($importfile);
4254  $found = $this->locateImportFiles($import_dir);
4255  if (!((strlen($found["dir"]) > 0) && (strlen($found["xml"]) > 0)))
4256  {
4257  $error = $this->lng->txt("wrong_import_file_structure");
4258  return $error;
4259  }
4260  $importfile = $found["xml"];
4261  $import_subdir = $found["dir"];
4262  }
4263  else
4264  {
4265  $importfile = tempnam($import_dir, "survey_import");
4266  ilUtil::moveUploadedFile($source, $file_info["name"], $importfile);
4267  }
4268  $fh = fopen($importfile, "r");
4269  if (!$fh)
4270  {
4271  $error = $this->lng->txt("import_error_opening_file");
4272  return $error;
4273  }
4274  $xml = fread($fh, filesize($importfile));
4275  $result = fclose($fh);
4276  if (!$result)
4277  {
4278  $error = $this->lng->txt("import_error_closing_file");
4279  return $error;
4280  }
4281 
4282  unset($_SESSION["import_mob_xhtml"]);
4283  if (strpos($xml, "questestinterop"))
4284  {
4285  include_once("./Modules/Survey/exceptions/class.ilInvalidSurveyImportFileException.php");
4286  throw new ilInvalidSurveyImportFileException("Unsupported survey version (< 3.8) found.");
4287  /*
4288  include_once "./Services/Survey/classes/class.SurveyImportParserPre38.php";
4289  $import = new SurveyImportParserPre38($svy_qpl_id, "", TRUE);
4290  $import->setSurveyObject($this);
4291  $import->setXMLContent($xml);
4292  $import->startParsing();*/
4293  }
4294  else
4295  {
4296  include_once "./Services/Survey/classes/class.SurveyImportParser.php";
4297  $import = new SurveyImportParser($svy_qpl_id, "", TRUE);
4298  $import->setSurveyObject($this);
4299  $import->setXMLContent($xml);
4300  $import->startParsing();
4301  }
4302 
4303  if (is_array($_SESSION["import_mob_xhtml"]))
4304  {
4305  include_once "./Services/MediaObjects/classes/class.ilObjMediaObject.php";
4306  include_once "./Services/RTE/classes/class.ilRTE.php";
4307  include_once "./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php";
4308  foreach ($_SESSION["import_mob_xhtml"] as $mob)
4309  {
4310  $importfile = $import_subdir . "/" . $mob["uri"];
4311  if (file_exists($importfile))
4312  {
4313  if (!$mob["type"])
4314  {
4315  $mob["type"] = "svy:html";
4316  }
4317 
4318  $media_object = ilObjMediaObject::_saveTempFileAsMediaObject(basename($importfile), $importfile, FALSE);
4319 
4320  // survey mob
4321  if ($mob["type"] == "svy:html")
4322  {
4323  ilObjMediaObject::_saveUsage($media_object->getId(), "svy:html", $this->getId());
4324  $this->setIntroduction(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $this->getIntroduction()));
4325  $this->setOutro(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $this->getOutro()));
4326  }
4327  // question mob
4328  else if($import->questions[$mob["id"]])
4329  {
4330  $new_qid = $import->questions[$mob["id"]];
4331  ilObjMediaObject::_saveUsage($media_object->getId(), $mob["type"], $new_qid);
4332  $new_question = SurveyQuestion::_instanciateQuestion($new_qid);
4333  $qtext = $new_question->getQuestiontext();
4334  $qtext = ilRTE::_replaceMediaObjectImageSrc($qtext, 0);
4335  $qtext = str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $qtext);
4336  $qtext = ilRTE::_replaceMediaObjectImageSrc($qtext, 1);
4337  $new_question->setQuestiontext($qtext);
4338  $new_question->saveToDb();
4339 
4340  // also fix existing original in pool
4341  if($new_question->getOriginalId())
4342  {
4343  $pool_question = SurveyQuestion::_instanciateQuestion($new_question->getOriginalId());
4344  $pool_question->setQuestiontext($qtext);
4345  $pool_question->saveToDb();
4346  }
4347  }
4348  }
4349  else
4350  {
4351  global $ilLog;
4352  $ilLog->write("Error: Could not open XHTML mob file for test introduction during test import. File $importfile does not exist!");
4353  }
4354  }
4357  $this->saveToDb();
4358  }
4359 
4360  // delete import directory
4362  }
4363  return $error;
4364  }
4365 
4374  public function cloneObject($a_target_id,$a_copy_id = 0)
4375  {
4376  global $ilDB;
4377 
4378  $this->loadFromDb();
4379 
4380  // Copy settings
4381  $newObj = parent::cloneObject($a_target_id,$a_copy_id);
4382  $this->cloneMetaData($newObj);
4383  $newObj->updateMetaData();
4384 
4385  $newObj->setAuthor($this->getAuthor());
4386  $newObj->setIntroduction($this->getIntroduction());
4387  $newObj->setOutro($this->getOutro());
4388  $newObj->setEvaluationAccess($this->getEvaluationAccess());
4389  $newObj->setStartDate($this->getStartDate());
4390  $newObj->setEndDate($this->getEndDate());
4391  $newObj->setInvitation($this->getInvitation());
4392  $newObj->setInvitationMode($this->getInvitationMode());
4393  $newObj->setAnonymize($this->getAnonymize());
4394  $newObj->setShowQuestionTitles($this->getShowQuestionTitles());
4395  $newObj->setTemplate($this->getTemplate());
4396  $newObj->setPoolUsage($this->getPoolUsage());
4397  $newObj->setViewOwnResults($this->hasViewOwnResults());
4398  $newObj->setMailOwnResults($this->hasMailOwnResults());
4399 
4400  // #12661
4401  if($this->get360Mode())
4402  {
4403  $newObj->set360Mode(true);
4404  $newObj->set360SelfEvaluation($this->get360SelfEvaluation());
4405  $newObj->set360SelfAppraisee($this->get360SelfAppraisee());
4406  $newObj->set360SelfRaters($this->get360SelfRaters());
4407  $newObj->set360Results($this->get360Results());
4408  $newObj->set360SkillService($this->get360SkillService());
4409  }
4410 
4411  // reminder/notification
4412  $newObj->setReminderStatus($this->getReminderStatus());
4413  $newObj->setReminderStart($this->getReminderStart());
4414  $newObj->setReminderEnd($this->getReminderEnd());
4415  $newObj->setReminderFrequency($this->getReminderFrequency());
4416  $newObj->setReminderTarget($this->getReminderTarget());
4417  // reminder_last_sent must not be copied!
4418  $newObj->setTutorNotificationStatus($this->getTutorNotificationStatus());
4419  $newObj->setTutorNotificationRecipients($this->getTutorNotificationRecipients());
4420  $newObj->setTutorNotificationTarget($this->getTutorNotificationTarget());
4421 
4422  $question_pointer = array();
4423  // clone the questions
4424  $mapping = array();
4425  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
4426 
4427  foreach ($this->questions as $key => $question_id)
4428  {
4429  $question = ilObjSurvey::_instanciateQuestion($question_id);
4430  if($question) // #10824
4431  {
4432  $question->id = -1;
4433  $original_id = SurveyQuestion::_getOriginalId($question_id, false);
4434  $question->saveToDb($original_id);
4435  $newObj->questions[$key] = $question->getId();
4436  $question_pointer[$question_id] = $question->getId();
4437  $mapping[$question_id] = $question->getId();
4438  }
4439  }
4440 
4441  //copy online status if object is not the root copy object
4442  $cp_options = ilCopyWizardOptions::_getInstance($a_copy_id);
4443 
4444  if(!$cp_options->isRootNode($this->getRefId()))
4445  {
4446  $newObj->setStatus($this->isOnline()?self::STATUS_ONLINE: self::STATUS_OFFLINE);
4447  }
4448 
4449  $newObj->saveToDb();
4450  $newObj->cloneTextblocks($mapping);
4451 
4452  // #14929
4453  if($this->get360Mode() &&
4454  $this->get360SkillService())
4455  {
4456  include_once "./Modules/Survey/classes/class.ilSurveySkill.php";
4457  $src_skills = new ilSurveySkill($this);
4458  $tgt_skills = new ilSurveySkill($newObj);
4459 
4460  foreach($mapping as $src_qst_id => $tgt_qst_id)
4461  {
4462  $qst_skill = $src_skills->getSkillForQuestion($src_qst_id);
4463  if($qst_skill)
4464  {
4465  $tgt_skills->addQuestionSkillAssignment($tgt_qst_id, $qst_skill["base_skill_id"], $qst_skill["tref_id"]);
4466  }
4467  }
4468  }
4469 
4470  // clone the questionblocks
4471  $questionblocks = array();
4472  $questionblock_questions = array();
4473  $result = $ilDB->queryF("SELECT * FROM svy_qblk_qst WHERE survey_fi = %s",
4474  array('integer'),
4475  array($this->getSurveyId())
4476  );
4477  if ($result->numRows() > 0)
4478  {
4479  while ($row = $ilDB->fetchAssoc($result))
4480  {
4481  array_push($questionblock_questions, $row);
4482  $questionblocks[$row["questionblock_fi"]] = $row["questionblock_fi"];
4483  }
4484  }
4485  // create new questionblocks
4486  foreach ($questionblocks as $key => $value)
4487  {
4488  $questionblock = ilObjSurvey::_getQuestionblock($key);
4489  $questionblock_id = ilObjSurvey::_addQuestionblock($questionblock["title"], $questionblock["owner_fi"], $questionblock["show_questiontext"], $questionblock["show_blocktitle"]);
4490  $questionblocks[$key] = $questionblock_id;
4491  }
4492  // create new questionblock questions
4493  foreach ($questionblock_questions as $key => $value)
4494  {
4495  if($questionblocks[$value["questionblock_fi"]] &&
4496  $question_pointer[$value["question_fi"]])
4497  {
4498  $next_id = $ilDB->nextId('svy_qblk_qst');
4499  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, question_fi) ".
4500  "VALUES (%s, %s, %s, %s)",
4501  array('integer','integer','integer','integer'),
4502  array($next_id, $newObj->getSurveyId(), $questionblocks[$value["questionblock_fi"]], $question_pointer[$value["question_fi"]])
4503  );
4504  }
4505  }
4506 
4507  // clone the constraints
4508  $constraints = ilObjSurvey::_getConstraints($this->getSurveyId());
4509  $newConstraints = array();
4510  foreach ($constraints as $key => $constraint)
4511  {
4512  if ($question_pointer[$constraint["for_question"]] &&
4513  $question_pointer[$constraint["question"]])
4514  {
4515  if (!array_key_exists($constraint['id'], $newConstraints))
4516  {
4517  $constraint_id = $newObj->addConstraint($question_pointer[$constraint["question"]], $constraint["relation_id"], $constraint["value"], $constraint['conjunction']);
4518  $newConstraints[$constraint['id']] = $constraint_id;
4519  }
4520  $newObj->addConstraintToQuestion($question_pointer[$constraint["for_question"]], $newConstraints[$constraint['id']]);
4521  }
4522  }
4523 
4524  // clone the obligatory states
4525  $result = $ilDB->queryF("SELECT * FROM svy_qst_oblig WHERE survey_fi = %s",
4526  array('integer'),
4527  array($this->getSurveyId())
4528  );
4529  if ($result->numRows() > 0)
4530  {
4531  while ($row = $ilDB->fetchAssoc($result))
4532  {
4533  if($question_pointer[$row["question_fi"]])
4534  {
4535  $next_id = $ilDB->nextId('svy_qst_oblig');
4536  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qst_oblig (question_obligatory_id, survey_fi, question_fi, ".
4537  "obligatory, tstamp) VALUES (%s, %s, %s, %s, %s)",
4538  array('integer','integer','integer','text','integer'),
4539  array($next_id, $newObj->getSurveyId(), $question_pointer[$row["question_fi"]], $row["obligatory"], time())
4540  );
4541  }
4542  }
4543  }
4544 
4545  // #16210 - clone LP settings
4546  include_once('./Services/Tracking/classes/class.ilLPObjSettings.php');
4547  $obj_settings = new ilLPObjSettings($this->getId());
4548  $obj_settings->cloneSettings($newObj->getId());
4549  unset($obj_settings);
4550 
4551  return $newObj;
4552  }
4553 
4554  function getTextblock($question_id)
4555  {
4556  global $ilDB;
4557  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE question_fi = %s",
4558  array('integer'),
4559  array($question_id)
4560  );
4561  if ($result->numRows())
4562  {
4563  $row = $ilDB->fetchAssoc($result);
4564  return $row["heading"];
4565  }
4566  else
4567  {
4568  return "";
4569  }
4570  }
4571 
4577  function cloneTextblocks($mapping)
4578  {
4579  foreach ($mapping as $original_id => $new_id)
4580  {
4581  $textblock = $this->getTextblock($original_id);
4582  include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php";
4583  $this->saveHeading(ilUtil::stripSlashes($textblock, TRUE, ilObjAdvancedEditing::_getUsedHTMLTagsAsString("survey")), $new_id);
4584  }
4585  }
4586 
4593  {
4594  include_once "./Services/Utilities/classes/class.ilUtil.php";
4595  $svy_data_dir = ilUtil::getDataDir()."/svy_data";
4596  ilUtil::makeDir($svy_data_dir);
4597  if(!is_writable($svy_data_dir))
4598  {
4599  $this->ilias->raiseError("Survey Data Directory (".$svy_data_dir
4600  .") not writeable.",$this->ilias->error_obj->FATAL);
4601  }
4602 
4603  // create learning module directory (data_dir/lm_data/lm_<id>)
4604  $svy_dir = $svy_data_dir."/svy_".$this->getId();
4605  ilUtil::makeDir($svy_dir);
4606  if(!@is_dir($svy_dir))
4607  {
4608  $this->ilias->raiseError("Creation of Survey Directory failed.",$this->ilias->error_obj->FATAL);
4609  }
4610  // create Export subdirectory (data_dir/lm_data/lm_<id>/Export)
4611  $export_dir = $svy_dir."/export";
4612  ilUtil::makeDir($export_dir);
4613  if(!@is_dir($export_dir))
4614  {
4615  $this->ilias->raiseError("Creation of Export Directory failed.",$this->ilias->error_obj->FATAL);
4616  }
4617  }
4618 
4623  {
4624  include_once "./Services/Utilities/classes/class.ilUtil.php";
4625  $export_dir = ilUtil::getDataDir()."/svy_data"."/svy_".$this->getId()."/export";
4626 
4627  return $export_dir;
4628  }
4629 
4636  {
4637  include_once "./Services/Utilities/classes/class.ilUtil.php";
4638  $svy_data_dir = ilUtil::getDataDir()."/svy_data";
4639  ilUtil::makeDir($svy_data_dir);
4640 
4641  if(!is_writable($svy_data_dir))
4642  {
4643  $this->ilias->raiseError("Survey Data Directory (".$svy_data_dir
4644  .") not writeable.",$this->ilias->error_obj->FATAL);
4645  }
4646 
4647  // create test directory (data_dir/svy_data/svy_<id>)
4648  $svy_dir = $svy_data_dir."/svy_".$this->getId();
4649  ilUtil::makeDir($svy_dir);
4650  if(!@is_dir($svy_dir))
4651  {
4652  $this->ilias->raiseError("Creation of Survey Directory failed.",$this->ilias->error_obj->FATAL);
4653  }
4654 
4655  // create import subdirectory (data_dir/svy_data/svy_<id>/import)
4656  $import_dir = $svy_dir."/import";
4657  ilUtil::makeDir($import_dir);
4658  if(!@is_dir($import_dir))
4659  {
4660  $this->ilias->raiseError("Creation of Import Directory failed.",$this->ilias->error_obj->FATAL);
4661  }
4662  }
4663 
4668  {
4669  include_once "./Services/Utilities/classes/class.ilUtil.php";
4670  $import_dir = ilUtil::getDataDir()."/svy_data".
4671  "/svy_".$this->getId()."/import";
4672  if (!is_dir($import_dir))
4673  {
4674  ilUtil::makeDirParents($import_dir);
4675  }
4676  if(@is_dir($import_dir))
4677  {
4678  return $import_dir;
4679  }
4680  else
4681  {
4682  return false;
4683  }
4684  }
4685 
4686  function saveHeading($heading = "", $insertbefore)
4687  {
4688  global $ilDB;
4689  if ($heading)
4690  {
4691  $affectedRows = $ilDB->manipulateF("UPDATE svy_svy_qst SET heading=%s WHERE survey_fi=%s AND question_fi=%s",
4692  array('text','integer','integer'),
4693  array($heading, $this->getSurveyId(), $insertbefore)
4694  );
4695  }
4696  else
4697  {
4698  $affectedRows = $ilDB->manipulateF("UPDATE svy_svy_qst SET heading=%s WHERE survey_fi=%s AND question_fi=%s",
4699  array('text','integer','integer'),
4700  array(NULL, $this->getSurveyId(), $insertbefore)
4701  );
4702  }
4703  }
4704 
4705  function isAnonymousKey($key)
4706  {
4707  global $ilDB;
4708 
4709  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_anonymous WHERE survey_key = %s AND survey_fi = %s",
4710  array('text','integer'),
4711  array($key, $this->getSurveyId())
4712  );
4713  return ($result->numRows() == 1) ? true : false;
4714  }
4715 
4716  function getUserSurveyCode($user_id)
4717  {
4718  global $ilDB;
4719 
4720  if (($user_id == ANONYMOUS_USER_ID) || (($this->isAccessibleWithoutCode() && $this->isAllowedToTakeMultipleSurveys()))) return "";
4721  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
4722  array('integer','integer'),
4723  array($this->getSurveyId(), $user_id)
4724  );
4725  if ($result->numRows() == 1)
4726  {
4727  $row = $ilDB->fetchAssoc($result);
4728  return $row["anonymous_id"];
4729  }
4730  else
4731  {
4732  return "";
4733  }
4734  }
4735 
4736  function bindSurveyCodeToUser($user_id, $code)
4737  {
4738  global $ilDB;
4739 
4740  if($user_id == ANONYMOUS_USER_ID)
4741  {
4742  return;
4743  }
4744 
4745  if($this->checkSurveyCode($code))
4746  {
4747  $ilDB->manipulate("UPDATE svy_anonymous".
4748  " SET user_key = ".$ilDB->quote(md5($user_id), "text").
4749  " WHERE survey_key = ".$ilDB->quote($code, "text"));
4750  }
4751  }
4752 
4754  {
4755  global $ilDB;
4756 
4757  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE anonymous_id = %s AND survey_fi = %s",
4758  array('text','integer'),
4759  array($key, $this->getSurveyId())
4760  );
4761  return ($result->numRows() == 1) ? true : false;
4762  }
4763 
4765  {
4766  if ($this->isAnonymousKey($code))
4767  {
4768  if ($this->isSurveyStarted("", $code) == 1)
4769  {
4770  return false;
4771  }
4772  else
4773  {
4774  return true;
4775  }
4776  }
4777  else
4778  {
4779  return false;
4780  }
4781  }
4782 
4790  {
4791  global $ilDB;
4792 
4793  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_anonymous WHERE survey_fi = %s AND user_key IS NULL",
4794  array('integer'),
4795  array($this->getSurveyId())
4796  );
4797  return $result->numRows();
4798  }
4799 
4807  function getSurveyCodesForExport(array $a_codes = null, array $a_ids = null)
4808  {
4809  global $ilDB, $ilUser, $lng;
4810 
4811  include_once "./Services/Link/classes/class.ilLink.php";
4812 
4813  $sql = "SELECT svy_anonymous.*, svy_finished.state".
4814  " FROM svy_anonymous".
4815  " LEFT JOIN svy_finished ON (svy_anonymous.survey_key = svy_finished.anonymous_id)".
4816  " WHERE svy_anonymous.survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer").
4817  " AND svy_anonymous.user_key IS NULL";
4818 
4819  if($a_codes)
4820  {
4821  $sql .= " AND ".$ilDB->in("svy_anonymous.survey_key", $a_codes, "", "text");
4822  }
4823  else if($a_ids)
4824  {
4825  $sql .= " AND ".$ilDB->in("svy_anonymous.anonymous_id", $a_ids, "", "text");
4826  }
4827 
4828  $export = array();
4829 
4830  // #14905
4831  $titles = array();
4832  $titles[] = '"'.$lng->txt("survey_code").'"';
4833  $titles[] = '"'.$lng->txt("email").'"';
4834  $titles[] = '"'.$lng->txt("lastname").'"';
4835  $titles[] = '"'.$lng->txt("firstname").'"';
4836  $titles[] = '"'.$lng->txt("create_date").'"';
4837  $titles[] = '"'.$lng->txt("used").'"';
4838  $titles[] = '"'.$lng->txt("mail_sent_short").'"';
4839  $titles[] = '"'.$lng->txt("survey_code_url").'"';
4840  $export[] = implode(";", $titles);
4841 
4842  $result = $ilDB->query($sql);
4843  $default_lang = $ilUser->getPref("survey_code_language");
4844  while ($row = $ilDB->fetchAssoc($result))
4845  {
4846  $item = array();
4847  $item[] = $row["survey_key"];
4848 
4849  if($row["externaldata"])
4850  {
4851  $ext = unserialize($row["externaldata"]);
4852  $item[] = $ext["email"];
4853  $item[] = $ext["lastname"];
4854  $item[] = $ext["firstname"];
4855  }
4856  else
4857  {
4858  $item[] = "";
4859  $item[] = "";
4860  $item[] = "";
4861  }
4862 
4863  // No relative (today, tomorrow...) dates in export.
4864  $date = new ilDateTime($row['tstamp'],IL_CAL_UNIX);
4865  $item[] = $date->get(IL_CAL_DATETIME);
4866 
4867  $item[] = ($this->isSurveyCodeUsed($row["survey_key"])) ? 1 : 0;
4868  $item[] = ($row["sent"]) ? 1 : 0;
4869 
4870  $params = array("accesscode" => $row["survey_key"]);
4871  if ($default_lang)
4872  {
4873  $params["lang"] = $default_lang;
4874  }
4875  $item[] = ilLink::_getLink($this->getRefId(), "svy", $params);
4876 
4877  $export[] = '"'.implode('";"', $item).'"';
4878  }
4879  return implode("\n", $export);
4880  }
4881 
4889  public function getSurveyCodesTableData(array $ids = null, $lang = null)
4890  {
4891  global $ilDB;
4892 
4893  include_once "./Services/Link/classes/class.ilLink.php";
4894 
4895  $codes = array();
4896 
4897  $sql = "SELECT svy_anonymous.*, svy_finished.state".
4898  " FROM svy_anonymous".
4899  " LEFT JOIN svy_finished ON (svy_anonymous.survey_key = svy_finished.anonymous_id)".
4900  " WHERE svy_anonymous.survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer") /*.
4901  " AND svy_anonymous.user_key IS NULL" */; // #15860
4902 
4903  if($ids)
4904  {
4905  $sql .= " AND ".$ilDB->in("svy_anonymous.anonymous_id", $ids, "", "integer");
4906  }
4907 
4908  $sql .= " ORDER BY tstamp, survey_key ASC";
4909  $result = $ilDB->query($sql);
4910  if ($result->numRows() > 0)
4911  {
4912  while ($row = $ilDB->fetchAssoc($result))
4913  {
4914  $href = "";
4915  $used = false;
4916  if ($this->isSurveyCodeUsed($row["survey_key"]))
4917  {
4918  $used = true;
4919  }
4920  else
4921  {
4922  $params = array("accesscode" => $row["survey_key"]);
4923  if ($lang)
4924  {
4925  $params["lang"] = $lang;
4926  }
4927  $href = ilLink::_getLink($this->getRefId(), "svy", $params);
4928  }
4929 
4930 
4931  $item = array(
4932  'id' => $row["anonymous_id"],
4933  'code' => $row["survey_key"],
4934  'date' => $row["tstamp"],
4935  'used' => $used,
4936  'sent' => $row['sent'],
4937  'href' => $href,
4938  'email' => '',
4939  'last_name' => '',
4940  'first_name' => ''
4941  );
4942 
4943  if($row["externaldata"])
4944  {
4945  $ext = unserialize($row["externaldata"]);
4946  $item['email'] = $ext['email'];
4947  $item['last_name'] = $ext['lastname'];
4948  $item['first_name'] = $ext['firstname'];
4949  }
4950 
4951  array_push($codes, $item);
4952  }
4953  }
4954  return $codes;
4955  }
4956 
4958  {
4959  global $ilDB;
4960  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s AND anonymous_id = %s",
4961  array('integer','text'),
4962  array($this->getSurveyId(), $code)
4963  );
4964  return ($result->numRows() > 0) ? true : false;
4965  }
4966 
4968  {
4969  global $ilDB;
4970  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_anonymous WHERE survey_fi = %s AND survey_key = %s",
4971  array('integer','text'),
4972  array($this->getSurveyId(), $code)
4973  );
4974  return ($result->numRows() > 0) ? false : true;
4975  }
4976 
4977  function createSurveyCodes($nrOfCodes)
4978  {
4979  global $ilDB;
4980 
4981  $res = array();
4982 
4983  for ($i = 0; $i < $nrOfCodes; $i++)
4984  {
4985  $next_id = $ilDB->nextId('svy_anonymous');
4986  $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, tstamp) ".
4987  "VALUES (%s, %s, %s, %s)",
4988  array('integer','text','integer','integer'),
4989  array($next_id, $this->createNewAccessCode(), $this->getSurveyId(), time())
4990  );
4991  $res[] = $next_id;
4992  }
4993 
4994  return $res;
4995  }
4996 
4997  function importSurveyCode($a_anonymize_key, $a_created, $a_data)
4998  {
4999  global $ilDB;
5000 
5001  $next_id = $ilDB->nextId('svy_anonymous');
5002  $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, externaldata, tstamp) ".
5003  "VALUES (%s, %s, %s, %s, %s)",
5004  array('integer','text','integer','text','integer'),
5005  array($next_id, $a_anonymize_key, $this->getSurveyId(), serialize($a_data), $a_created)
5006  );
5007  }
5008 
5010  {
5011  global $ilDB;
5012 
5013  $ids = array();
5014  foreach ($data as $dataset)
5015  {
5016  $anonymize_key = $this->createNewAccessCode();
5017  $next_id = $ilDB->nextId('svy_anonymous');
5018  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, externaldata, tstamp) ".
5019  "VALUES (%s, %s, %s, %s, %s)",
5020  array('integer','text','integer','text','integer'),
5021  array($next_id, $anonymize_key, $this->getSurveyId(), serialize($dataset), time())
5022  );
5023  $ids[] = $next_id;
5024  }
5025  return $ids;
5026  }
5027 
5028  function sendCodes($not_sent, $subject, $message, $lang)
5029  {
5030  /*
5031  * 0 = all
5032  * 1 = not sent
5033  * 2 = finished
5034  * 3 = not finished
5035  */
5036  $check_finished = ($not_sent > 1);
5037 
5038  include_once "./Services/Mail/classes/class.ilMail.php";
5039  include_once "./Services/Link/classes/class.ilLink.php";
5040  $user_id = $this->getOwner();
5041  $mail = new ilMail($user_id);
5042  $recipients = $this->getExternalCodeRecipients($check_finished);
5043  foreach ($recipients as $data)
5044  {
5045  if($data['email'] && $data['code'])
5046  {
5047  $do_send = false;
5048  switch ((int)$not_sent)
5049  {
5050  case 1:
5051  $do_send = !(bool)$data['sent'];
5052  break;
5053 
5054  case 2:
5055  $do_send = $data['finished'];
5056  break;
5057 
5058  case 3:
5059  $do_send = !$data['finished'];
5060  break;
5061 
5062  default:
5063  $do_send = true;
5064  break;
5065  }
5066  if ($do_send)
5067  {
5068  // build text
5069  $messagetext = $message;
5070  $url = ilLink::_getLink($this->getRefId(), "svy",
5071  array(
5072  "accesscode" => $data["code"],
5073  "lang" => $lang
5074  ));
5075  $messagetext = str_replace('[url]', "<" . $url . ">", $messagetext);
5076  foreach ($data as $key => $value)
5077  {
5078  $messagetext = str_replace('[' . $key . ']', $value, $messagetext);
5079  }
5080 
5081  // send mail
5082  $mail->sendMail(
5083  $data['email'], // to
5084  "", // cc
5085  "", // bcc
5086  $subject, // subject
5087  $messagetext, // message
5088  array(), // attachments
5089  array('normal') // type
5090  );
5091  }
5092  }
5093  }
5094 
5095  global $ilDB;
5096  $ilDB->manipulateF("UPDATE svy_anonymous SET sent = %s WHERE survey_fi = %s AND externaldata IS NOT NULL",
5097  array('integer','integer'),
5098  array(1, $this->getSurveyId())
5099  );
5100  }
5101 
5102  function getExternalCodeRecipients($a_check_finished = false)
5103  {
5104  global $ilDB;
5105  $result = $ilDB->queryF("SELECT survey_key code, externaldata, sent FROM svy_anonymous WHERE survey_fi = %s",
5106  array('integer'),
5107  array($this->getSurveyId())
5108  );
5109  $res = array();
5110  while ($row = $ilDB->fetchAssoc($result))
5111  {
5112  if(!$row['externaldata'])
5113  {
5114  continue;
5115  }
5116 
5117  $externaldata = unserialize($row['externaldata']);
5118  if(!$externaldata['email'])
5119  {
5120  continue;
5121  }
5122 
5123  $externaldata['code'] = $row['code'];
5124  $externaldata['sent'] = $row['sent'];
5125 
5126  if($a_check_finished)
5127  {
5128  $externaldata['finished'] = $this->isSurveyCodeUsed($row['code']);
5129  }
5130 
5131  array_push($res, $externaldata);
5132  }
5133  return $res;
5134  }
5135 
5141  function deleteSurveyCode($survey_code)
5142  {
5143  global $ilDB;
5144 
5145  if (strlen($survey_code) > 0)
5146  {
5147  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_anonymous WHERE survey_fi = %s AND survey_key = %s",
5148  array('integer', 'text'),
5149  array($this->getSurveyId(), $survey_code)
5150  );
5151  }
5152  }
5153 
5160  function getUserAccessCode($user_id)
5161  {
5162  global $ilDB;
5163  $access_code = "";
5164  $result = $ilDB->queryF("SELECT survey_key FROM svy_anonymous WHERE survey_fi = %s AND user_key = %s",
5165  array('integer','text'),
5166  array($this->getSurveyId(), md5($user_id))
5167  );
5168  if ($result->numRows())
5169  {
5170  $row = $ilDB->fetchAssoc($result);
5171  $access_code = $row["survey_key"];
5172  }
5173  return $access_code;
5174  }
5175 
5182  function saveUserAccessCode($user_id, $access_code)
5183  {
5184  global $ilDB;
5185 
5186  // not really sure what to do about ANONYMOUS_USER_ID
5187 
5188  $next_id = $ilDB->nextId('svy_anonymous');
5189  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, user_key, tstamp) ".
5190  "VALUES (%s, %s, %s, %s, %s)",
5191  array('integer','text', 'integer', 'text', 'integer'),
5192  array($next_id, $access_code, $this->getSurveyId(), md5($user_id), time())
5193  );
5194  }
5195 
5202  {
5203  // create a 5 character code
5204  $codestring = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
5205  mt_srand();
5206  $code = "";
5207  for ($i = 1; $i <=5; $i++)
5208  {
5209  $index = mt_rand(0, strlen($codestring)-1);
5210  $code .= substr($codestring, $index, 1);
5211  }
5212  // verify it against the database
5213  while (!$this->isSurveyCodeUnique($code))
5214  {
5215  $code = $this->createNewAccessCode();
5216  }
5217  return $code;
5218  }
5219 
5220 
5231  function &processCSVRow($row, $quoteAll = FALSE, $separator = ";")
5232  {
5233  $resultarray = array();
5234  foreach ($row as $rowindex => $entry)
5235  {
5236  if(is_array($entry))
5237  {
5238  $entry = implode("/", $entry);
5239  }
5240  $surround = FALSE;
5241  if ($quoteAll)
5242  {
5243  $surround = TRUE;
5244  }
5245  if (strpos($entry, "\"") !== FALSE)
5246  {
5247  $entry = str_replace("\"", "\"\"", $entry);
5248  $surround = TRUE;
5249  }
5250  if (strpos($entry, $separator) !== FALSE)
5251  {
5252  $surround = TRUE;
5253  }
5254  // replace all CR LF with LF (for Excel for Windows compatibility
5255  $entry = str_replace(chr(13).chr(10), chr(10), $entry);
5256  if ($surround)
5257  {
5258  $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
5259  }
5260  else
5261  {
5262  $resultarray[$rowindex] = utf8_decode($entry);
5263  }
5264  }
5265  return $resultarray;
5266  }
5267 
5268  function _getLastAccess($finished_id)
5269  {
5270  global $ilDB;
5271 
5272  $result = $ilDB->queryF("SELECT tstamp FROM svy_answer WHERE active_fi = %s ORDER BY tstamp DESC",
5273  array('integer'),
5274  array($finished_id)
5275  );
5276  if ($result->numRows())
5277  {
5278  $row = $ilDB->fetchAssoc($result);
5279  return $row["tstamp"];
5280  }
5281  else
5282  {
5283  $result = $ilDB->queryF("SELECT tstamp FROM svy_finished WHERE finished_id = %s",
5284  array('integer'),
5285  array($finished_id)
5286  );
5287  if ($result->numRows())
5288  {
5289  $row = $ilDB->fetchAssoc($result);
5290  return $row["tstamp"];
5291  }
5292  }
5293  return "";
5294  }
5295 
5302  function prepareTextareaOutput($txt_output)
5303  {
5304  include_once "./Services/Utilities/classes/class.ilUtil.php";
5305  return ilUtil::prepareTextareaOutput($txt_output, $prepare_for_latex_output);
5306  }
5307 
5315  function isHTML($a_text)
5316  {
5317  if (preg_match("/<[^>]*?>/", $a_text))
5318  {
5319  return TRUE;
5320  }
5321  else
5322  {
5323  return FALSE;
5324  }
5325  }
5326 
5335  function addMaterialTag(&$a_xml_writer, $a_material, $close_material_tag = TRUE, $add_mobs = TRUE, $attribs = NULL)
5336  {
5337  include_once "./Services/RTE/classes/class.ilRTE.php";
5338  include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php");
5339 
5340  $a_xml_writer->xmlStartTag("material", $attribs);
5341  $attrs = array(
5342  "type" => "text/plain"
5343  );
5344  if ($this->isHTML($a_material))
5345  {
5346  $attrs["type"] = "text/xhtml";
5347  }
5348  $mattext = ilRTE::_replaceMediaObjectImageSrc($a_material, 0);
5349  $a_xml_writer->xmlElement("mattext", $attrs, $mattext);
5350 
5351  if ($add_mobs)
5352  {
5353  $mobs = ilObjMediaObject::_getMobsOfObject("svy:html", $this->getId());
5354  foreach ($mobs as $mob)
5355  {
5356  $mob_id = "il_" . IL_INST_ID . "_mob_" . $mob;
5357  if (strpos($mattext, $mob_id) !== FALSE)
5358  {
5359  $mob_obj =& new ilObjMediaObject($mob);
5360  $imgattrs = array(
5361  "label" => $mob_id,
5362  "uri" => "objects/" . "il_" . IL_INST_ID . "_mob_" . $mob . "/" . $mob_obj->getTitle(),
5363  "type" => "svy:html",
5364  "id" => $this->getId()
5365  );
5366  $a_xml_writer->xmlElement("matimage", $imgattrs, NULL);
5367  }
5368  }
5369  }
5370  if ($close_material_tag) $a_xml_writer->xmlEndTag("material");
5371  }
5372 
5382  {
5383  if ($this->getAnonymize() != self::ANONYMIZE_OFF)
5384  {
5385  if ($this->surveyCodeSecurity == FALSE)
5386  {
5387  return TRUE;
5388  }
5389  }
5390  return FALSE;
5391  }
5392 
5400  function processPrintoutput2FO($print_output)
5401  {
5402  global $ilLog;
5403 
5404  if (extension_loaded("tidy"))
5405  {
5406  $config = array(
5407  "indent" => false,
5408  "output-xml" => true,
5409  "numeric-entities" => true
5410  );
5411  $tidy = new tidy();
5412  $tidy->parseString($print_output, $config, 'utf8');
5413  $tidy->cleanRepair();
5414  $print_output = tidy_get_output($tidy);
5415  $print_output = preg_replace("/^.*?(<html)/", "\\1", $print_output);
5416  }
5417  else
5418  {
5419  $print_output = str_replace("&nbsp;", "&#160;", $print_output);
5420  $print_output = str_replace("&otimes;", "X", $print_output);
5421 
5422  // #17680 - metric questions use &#160; in print view
5423  $print_output = str_replace("&gt;", ">", $print_output);
5424  $print_output = str_replace("&lt;", "<", $print_output);
5425  $print_output = str_replace("&#160;", "~|nbsp|~", $print_output);
5426  $print_output = preg_replace('/&(?!amp)/', '&amp;', $print_output);
5427  $print_output = str_replace("~|nbsp|~", "&#160;", $print_output);
5428  }
5429  $xsl = file_get_contents("./Modules/Survey/xml/question2fo.xsl");
5430 
5431  // additional font support
5432  $xsl = str_replace(
5433  'font-family="Helvetica, unifont"',
5434  'font-family="'.$GLOBALS['ilSetting']->get('rpc_pdf_font','Helvetica, unifont').'"',
5435  $xsl
5436  );
5437 
5438  $args = array( '/_xml' => $print_output, '/_xsl' => $xsl );
5439  $xh = xslt_create();
5440  $params = array();
5441  $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", NULL, $args, $params);
5442  xslt_error($xh);
5443  xslt_free($xh);
5444  $ilLog->write($output);
5445  return $output;
5446  }
5447 
5454  function deliverPDFfromFO($fo)
5455  {
5456  global $ilLog;
5457 
5458  include_once "./Services/Utilities/classes/class.ilUtil.php";
5459  $fo_file = ilUtil::ilTempnam() . ".fo";
5460  $fp = fopen($fo_file, "w"); fwrite($fp, $fo); fclose($fp);
5461 
5462  include_once './Services/WebServices/RPC/classes/class.ilRpcClientFactory.php';
5463  try
5464  {
5465  $pdf_base64 = ilRpcClientFactory::factory('RPCTransformationHandler')->ilFO2PDF($fo);
5466  ilUtil::deliverData($pdf_base64->scalar, ilUtil::getASCIIFilename($this->getTitle()) . ".pdf", "application/pdf");
5467  return true;
5468  }
5469  catch(XML_RPC2_FaultException $e)
5470  {
5471  $ilLog->write(__METHOD__.': '.$e->getMessage());
5472  return false;
5473  }
5474  catch(Exception $e)
5475  {
5476  $ilLog->write(__METHOD__.': '.$e->getMessage());
5477  return false;
5478  }
5479 
5480  /*
5481  include_once "./Services/Transformation/classes/class.ilFO2PDF.php";
5482  $fo2pdf = new ilFO2PDF();
5483  $fo2pdf->setFOString($fo);
5484  $result = $fo2pdf->send();
5485  ilUtil::deliverData($result, ilUtil::getASCIIFilename($this->getTitle()) . ".pdf", "application/pdf");
5486  */
5487  }
5488 
5495  function isPluginActive($a_pname)
5496  {
5497  global $ilPluginAdmin;
5498  if ($ilPluginAdmin->isActive(IL_COMP_MODULE, "SurveyQuestionPool", "svyq", $a_pname))
5499  {
5500  return TRUE;
5501  }
5502  else
5503  {
5504  return FALSE;
5505  }
5506  }
5507 
5513  public function setSurveyId($survey_id)
5514  {
5515  $this->survey_id = $survey_id;
5516  }
5517 
5524  public function &getUserData($ids)
5525  {
5526  global $ilDB;
5527 
5528  if (!is_array($ids) || count($ids) ==0) return array();
5529 
5530  $result = $ilDB->query("SELECT usr_id, login, lastname, firstname FROM usr_data WHERE " . $ilDB->in('usr_id', $ids, false, 'integer') . " ORDER BY login");
5531  $result_array = array();
5532  while ($row = $ilDB->fetchAssoc($result))
5533  {
5534  $result_array[$row["usr_id"]]= $row;
5535  }
5536  return $result_array;
5537  }
5538 
5539  function &getGroupData($ids)
5540  {
5541  if (!is_array($ids) || count($ids) ==0) return array();
5542  $result = array();
5543  foreach ($ids as $ref_id)
5544  {
5545  $obj_id = ilObject::_lookupObjId($ref_id);
5546  $result[$ref_id] = array("ref_id" => $ref_id, "title" => ilObject::_lookupTitle($obj_id), "description" => ilObject::_lookupDescription($obj_id));
5547  }
5548  return $result;
5549  }
5550 
5551  function &getRoleData($ids)
5552  {
5553  if (!is_array($ids) || count($ids) ==0) return array();
5554  $result = array();
5555  foreach ($ids as $obj_id)
5556  {
5557  $result[$obj_id] = array("obj_id" => $obj_id, "title" => ilObject::_lookupTitle($obj_id), "description" => ilObject::_lookupDescription($obj_id));
5558  }
5559  return $result;
5560  }
5561 
5563  {
5564  return $this->mailnotification;
5565  }
5566 
5567  function setMailNotification($a_notification)
5568  {
5569  $this->mailnotification = ($a_notification) ? true : false;
5570  }
5571 
5572  function getMailAddresses()
5573  {
5574  return $this->mailaddresses;
5575  }
5576 
5577  function setMailAddresses($a_addresses)
5578  {
5579  $this->mailaddresses = $a_addresses;
5580  }
5581 
5583  {
5585  }
5586 
5587  function setMailParticipantData($a_data)
5588  {
5589  $this->mailparticipantdata = $a_data;
5590  }
5591 
5592  public function getSurveyTimes()
5593  {
5594  global $ilDB;
5595 
5596  $result = $ilDB->queryF("SELECT * FROM svy_times, svy_finished WHERE svy_finished.survey_fi = %s",
5597  array('integer'),
5598  array($this->getId())
5599  );
5600  $times = array();;
5601  while ($row = $ilDB->fetchAssoc($result))
5602  {
5603  if (strlen($row['left_page']) && strlen($row['entered_page']))
5604  $times[$row['finished_fi']] += ($row['left_page']-$row['entered_page']);
5605  }
5606  return $times;
5607  }
5608 
5609  function setStartTime($finished_id, $first_question)
5610  {
5611  global $ilDB;
5612  $time = time();
5613  //primary for table svy_times
5614  $id = $ilDB->nextId('svy_times');
5615  $_SESSION['svy_entered_page'] = $time;
5616  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_times (id, finished_fi, entered_page, left_page, first_question) VALUES (%s, %s, %s, %s,%s)",
5617  array('integer','integer', 'integer', 'integer', 'integer'),
5618  array($id, $finished_id, $time, NULL, $first_question)
5619  );
5620  }
5621 
5622  function setEndTime($finished_id)
5623  {
5624  global $ilDB;
5625  $time = time();
5626  $affectedRows = $ilDB->manipulateF("UPDATE svy_times SET left_page = %s WHERE finished_fi = %s AND entered_page = %s",
5627  array('integer', 'integer', 'integer'),
5628  array($time, $finished_id, $_SESSION['svy_entered_page'])
5629  );
5630  unset($_SESSION['svy_entered_page']);
5631  }
5632 
5633  function getWorkingtimeForParticipant($finished_id)
5634  {
5635  global $ilDB;
5636 
5637  $result = $ilDB->queryF("SELECT * FROM svy_times WHERE finished_fi = %s",
5638  array('integer'),
5639  array($finished_id)
5640  );
5641  $total = 0;
5642  while ($row = $ilDB->fetchAssoc($result))
5643  {
5644  if ($row['left_page'] > 0 && $row['entered_page'] > 0)
5645  $total += $row['left_page'] - $row['entered_page'];
5646  }
5647  return $total;
5648  }
5649 
5650  function setTemplate($template_id)
5651  {
5652  $this->template_id = (int)$template_id;
5653  }
5654 
5655  function getTemplate()
5656  {
5657  return $this->template_id;
5658  }
5659 
5660  function updateOrder(array $a_order)
5661  {
5662  if(sizeof($this->questions) == sizeof($a_order))
5663  {
5664  $this->questions = array_flip($a_order);
5665  $this->saveQuestionsToDB();
5666  }
5667  }
5668 
5669  function getPoolUsage()
5670  {
5671  return $this->pool_usage;
5672  }
5673 
5674  function setPoolUsage($a_value)
5675  {
5676  $this->pool_usage = (bool)$a_value;
5677  }
5678 
5684  function isPoolActive()
5685  {
5686  $use_pool = (bool)$this->getPoolUsage();
5687  $template_settings = $this->getTemplate();
5688  if($template_settings)
5689  {
5690  include_once "Services/Administration/classes/class.ilSettingsTemplate.php";
5691  $template_settings = new ilSettingsTemplate($template_settings);
5692  $template_settings = $template_settings->getSettings();
5693  $template_settings = $template_settings["use_pool"];
5694  if($template_settings && $template_settings["hide"])
5695  {
5696  $use_pool = (bool)$template_settings["value"];
5697  }
5698  }
5699  return $use_pool;
5700  }
5701 
5707  function applySettingsTemplate($template_id)
5708  {
5709  if(!$template_id)
5710  {
5711  return;
5712  }
5713 
5714  include_once "Services/Administration/classes/class.ilSettingsTemplate.php";
5715  $template = new ilSettingsTemplate($template_id);
5716  $template_settings = $template->getSettings();
5717  if($template_settings)
5718  {
5719  if($template_settings["show_question_titles"] !== NULL)
5720  {
5721  if($template_settings["show_question_titles"]["value"])
5722  {
5723  $this->setShowQuestionTitles(true);
5724  }
5725  else
5726  {
5727  $this->setShowQuestionTitles(false);
5728  }
5729  }
5730 
5731  if($template_settings["use_pool"] !== NULL)
5732  {
5733  if($template_settings["use_pool"]["value"])
5734  {
5735  $this->setPoolUsage(true);
5736  }
5737  else
5738  {
5739  $this->setPoolUsage(false);
5740  }
5741  }
5742 
5743  if($template_settings["anonymization_options"]["value"])
5744  {
5745  $anon_map = array('personalized' => self::ANONYMIZE_OFF,
5746  'anonymize_with_code' => self::ANONYMIZE_ON,
5747  'anonymize_without_code' => self::ANONYMIZE_FREEACCESS);
5748  $this->setAnonymize($anon_map[$template_settings["anonymization_options"]["value"]]);
5749  }
5750 
5751  /* other settings: not needed here
5752  * - enabled_end_date
5753  * - enabled_start_date
5754  * - rte_switch
5755  */
5756  }
5757 
5758  $this->setTemplate($template_id);
5759  $this->saveToDb();
5760  }
5761 
5762  public function updateCode($a_id, $a_email, $a_last_name, $a_first_name, $a_sent)
5763  {
5764  global $ilDB;
5765 
5766  $a_email = trim($a_email);
5767 
5768  // :TODO:
5769  if($a_email && !ilUtil::is_email($a_email))
5770  {
5771  return;
5772  }
5773 
5774  $data = array("email" => $a_email,
5775  "lastname" => trim($a_last_name),
5776  "firstname" => trim($a_first_name));
5777 
5778  $fields = array(
5779  "externaldata" => array("text", serialize($data)),
5780  "sent" => array("integer", $a_sent)
5781  );
5782 
5783  $ilDB->update("svy_anonymous", $fields,
5784  array("anonymous_id" => array("integer", $a_id)));
5785  }
5786 
5787 
5788  //
5789  // 360°
5790  //
5791 
5792  public function set360Mode($a_value)
5793  {
5794  $this->mode_360 = (bool)$a_value;
5795  }
5796 
5797  public function get360Mode()
5798  {
5799  return (bool)$this->mode_360;
5800  }
5801 
5802  public function set360SelfEvaluation($a_value)
5803  {
5804  $this->mode_360_self_eval = (bool)$a_value;
5805  }
5806 
5807  public function get360SelfEvaluation()
5808  {
5809  return (bool)$this->mode_360_self_eval;
5810  }
5811 
5812  public function set360SelfAppraisee($a_value)
5813  {
5814  $this->mode_360_self_appr = (bool)$a_value;
5815  }
5816 
5817  public function get360SelfAppraisee()
5818  {
5819  return (bool)$this->mode_360_self_appr;
5820  }
5821 
5822  public function set360SelfRaters($a_value)
5823  {
5824  $this->mode_360_self_rate = (bool)$a_value;
5825  }
5826 
5827  public function get360SelfRaters()
5828  {
5829  return (bool)$this->mode_360_self_rate;
5830  }
5831 
5832  public function set360Results($a_value)
5833  {
5834  $this->mode_360_results = (int)$a_value;
5835  }
5836 
5837  public function get360Results()
5838  {
5839  return (int)$this->mode_360_results;
5840  }
5841 
5842  public function addAppraisee($a_user_id)
5843  {
5844  global $ilDB;
5845 
5846  if(!$this->isAppraisee($a_user_id) &&
5847  $a_user_id != ANONYMOUS_USER_ID)
5848  {
5849  $fields = array(
5850  "obj_id" => array("integer", $this->getSurveyId()),
5851  "user_id" => array("integer", $a_user_id)
5852  );
5853  $ilDB->insert("svy_360_appr", $fields);
5854  }
5855  }
5856 
5857  public function isAppraisee($a_user_id)
5858  {
5859  global $ilDB;
5860 
5861  $set = $ilDB->query("SELECT user_id".
5862  " FROM svy_360_appr".
5863  " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer").
5864  " AND user_id = ".$ilDB->quote($a_user_id, "integer"));
5865  return (bool)$ilDB->numRows($set);
5866  }
5867 
5868  public function isAppraiseeClosed($a_user_id)
5869  {
5870  global $ilDB;
5871 
5872  $set = $ilDB->query("SELECT has_closed".
5873  " FROM svy_360_appr".
5874  " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer").
5875  " AND user_id = ".$ilDB->quote($a_user_id, "integer"));
5876  $row = $ilDB->fetchAssoc($set);
5877  return $row["has_closed"];
5878  }
5879 
5880  public function deleteAppraisee($a_user_id)
5881  {
5882  global $ilDB;
5883 
5884  $ilDB->manipulate("DELETE FROM svy_360_appr".
5885  " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer").
5886  " AND user_id = ".$ilDB->quote($a_user_id, "integer"));
5887 
5888  $set = $ilDB->query("SELECT user_id".
5889  " FROM svy_360_rater".
5890  " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer").
5891  " AND appr_id = ".$ilDB->quote($a_user_id, "integer"));
5892  while($row = $ilDB->fetchAssoc($set))
5893  {
5894  $this->deleteRater($a_user_id, $row["user_id"]);
5895  }
5896  // appraisee will not be part of raters table
5897  if($this->get360SelfEvaluation())
5898  {
5899  $this->deleteRater($a_user_id, $a_user_id);
5900  }
5901  }
5902 
5903  public function getAppraiseesData()
5904  {
5905  global $ilDB;
5906 
5907  $res = array();
5908 
5909  $set = $ilDB->query("SELECT * FROM svy_360_appr".
5910  " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer"));
5911  while($row = $ilDB->fetchAssoc($set))
5912  {
5913  $name = ilObjUser::_lookupName($row["user_id"]);
5914  $name["email"] = ilObjUser::_lookupEmail($row["user_id"]);
5915  $name["name"] = $name["lastname"].", ".$name["firstname"];
5916  $res[$row["user_id"]] = $name;
5917 
5918  $finished = 0;
5919  $raters = $this->getRatersData($row["user_id"]);
5920  foreach($raters as $rater)
5921  {
5922  if($rater["finished"])
5923  {
5924  $finished++;
5925  }
5926  }
5927  $res[$row["user_id"]]["finished"] = $finished."/".sizeof($raters);
5928  $res[$row["user_id"]]["closed"] = $row["has_closed"];
5929  }
5930 
5931  return $res;
5932  }
5933 
5934  public function addRater($a_appraisee_id, $a_user_id, $a_anonymous_id = 0)
5935  {
5936  global $ilDB;
5937 
5938  if($this->isAppraisee($a_appraisee_id) &&
5939  !$this->isRater($a_appraisee_id, $a_user_id, $a_anonymous_id))
5940  {
5941  $fields = array(
5942  "obj_id" => array("integer", $this->getSurveyId()),
5943  "appr_id" => array("integer", $a_appraisee_id),
5944  "user_id" => array("integer", $a_user_id),
5945  "anonymous_id" => array("integer", $a_anonymous_id)
5946  );
5947  $ilDB->insert("svy_360_rater", $fields);
5948  }
5949  }
5950 
5951  public function isRater($a_appraisee_id, $a_user_id, $a_anonymous_id = 0)
5952  {
5953  global $ilDB;
5954 
5955  // user is rater if already appraisee and active self-evaluation
5956  if($this->isAppraisee($a_user_id) &&
5957  $this->get360SelfEvaluation() &&
5958  (!$a_appraisee_id || $a_appraisee_id == $a_user_id))
5959  {
5960  return true;
5961  }
5962 
5963  // :TODO: should we get rid of code as well?
5964 
5965  $sql = "SELECT user_id".
5966  " FROM svy_360_rater".
5967  " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer").
5968  " AND user_id = ".$ilDB->quote($a_user_id, "integer").
5969  " AND anonymous_id = ".$ilDB->quote($a_anonymous_id, "integer");
5970  if($a_appraisee_id)
5971  {
5972  $sql .= " AND appr_id = ".$ilDB->quote($a_appraisee_id, "integer");
5973  }
5974  $set = $ilDB->query($sql);
5975  return (bool)$ilDB->numRows($set);
5976  }
5977 
5978  public function deleteRater($a_appraisee_id, $a_user_id, $a_anonymous_id = 0)
5979  {
5980  global $ilDB;
5981 
5982  $finished_id = $this->getFinishedIdForAppraiseeIdAndRaterId($a_appraisee_id, $a_user_id);
5983  if($finished_id)
5984  {
5985  $this->removeSelectedSurveyResults(array($finished_id));
5986  }
5987 
5988  $ilDB->manipulate("DELETE FROM svy_360_rater".
5989  " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer").
5990  " AND appr_id = ".$ilDB->quote($a_appraisee_id, "integer").
5991  " AND user_id = ".$ilDB->quote($a_user_id, "integer").
5992  " AND anonymous_id = ".$ilDB->quote($a_anonymous_id, "integer"));
5993  }
5994 
5995  public function getRatersData($a_appraisee_id)
5996  {
5997  global $ilDB;
5998 
5999  $res = $anonymous_ids = array();
6000 
6001  $set = $ilDB->query("SELECT * FROM svy_360_rater".
6002  " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer").
6003  " AND appr_id = ".$ilDB->quote($a_appraisee_id, "integer"));
6004  while($row = $ilDB->fetchAssoc($set))
6005  {
6006  if($row["anonymous_id"])
6007  {
6008  $res["a".$row["anonymous_id"]] = array(
6009  "lastname" => "unknown code ".$row["anonymous_id"],
6010  "sent" => $row["mail_sent"],
6011  "finished" => null
6012  );
6013  $anonymous_ids[] = $row["anonymous_id"];
6014  }
6015  else
6016  {
6017  $name = ilObjUser::_lookupName($row["user_id"]);
6018  $name["user_id"] = "u".$name["user_id"];
6019  $name["email"] = ilObjUser::_lookupEmail($row["user_id"]);
6020  $name["sent"] = $row["mail_sent"];
6021  $name["finished"] = (bool)$this->is360SurveyStarted($a_appraisee_id, $row["user_id"]);
6022  $res["u".$row["user_id"]] = $name;
6023  }
6024  }
6025 
6026  if(sizeof($anonymous_ids))
6027  {
6028  $data = $this->getSurveyCodesTableData($anonymous_ids);
6029  foreach($data as $item)
6030  {
6031  if(isset($res["a".$item["id"]]))
6032  {
6033  $res["a".$item["id"]] = array(
6034  "user_id" => "a".$item["id"],
6035  "lastname" => $item["last_name"],
6036  "firstname" => $item["first_name"],
6037  "login" => "",
6038  "email" => $item["email"],
6039  "code" => $item["code"],
6040  "href" => $item["href"],
6041  "sent" => $res["a".$item["id"]]["sent"],
6042  "finished" => (bool)$this->is360SurveyStarted($a_appraisee_id, null, $item["code"])
6043  );
6044  }
6045  }
6046  }
6047 
6048  return $res;
6049  }
6050 
6051  public function getAppraiseesToRate($a_user_id, $a_anonymous_id = null)
6052  {
6053  global $ilDB;
6054 
6055  $res = array();
6056 
6057  $sql = "SELECT appr_id FROM svy_360_rater".
6058  " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer");
6059 
6060  if($a_user_id)
6061  {
6062  $sql .= " AND user_id = ".$ilDB->quote($a_user_id, "integer");
6063  }
6064  else
6065  {
6066  $sql .= " AND anonymous_id = ".$ilDB->quote($a_anonymous_id, "integer");
6067  }
6068 
6069  $set = $ilDB->query($sql);
6070  while($row = $ilDB->fetchAssoc($set))
6071  {
6072  $res[] = $row["appr_id"];
6073  }
6074 
6075  // user may evaluate himself if already appraisee
6076  if($this->get360SelfEvaluation() &&
6077  $this->isAppraisee($a_user_id) &&
6078  !in_array($a_user_id, $res))
6079  {
6080  $res[] = $a_user_id;
6081  }
6082 
6083  return $res;
6084  }
6085 
6086  public function getAnonymousIdByCode($a_code)
6087  {
6088  global $ilDB;
6089 
6090  $set = $ilDB->query("SELECT anonymous_id FROM svy_anonymous".
6091  " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer").
6092  " AND survey_key = ".$ilDB->quote($a_code, "text"));
6093  $res = $ilDB->fetchAssoc($set);
6094  return $res["anonymous_id"];
6095  }
6096 
6097  function is360SurveyStarted($appr_id, $user_id, $anonymous_code = null)
6098  {
6099  global $ilDB;
6100 
6101  $sql = "SELECT * FROM svy_finished".
6102  " WHERE survey_fi =".$ilDB->quote($this->getSurveyId(), "integer").
6103  " AND appr_id = ".$ilDB->quote($appr_id, "integer");
6104  if ($user_id)
6105  {
6106  $sql .= " AND user_fi = ".$ilDB->quote($user_id, "integer");
6107  }
6108  else
6109  {
6110  $sql .= " AND anonymous_id = ".$ilDB->quote($anonymous_code, "text");
6111  }
6112  $result = $ilDB->query($sql);
6113  if ($result->numRows() == 0)
6114  {
6115  return false;
6116  }
6117  else
6118  {
6119  $row = $ilDB->fetchAssoc($result);
6120  return (int)$row["state"];
6121  }
6122  }
6123 
6124  function getUserSurveyExecutionStatus($a_code = null)
6125  {
6126  global $ilUser, $ilDB;
6127 
6128  $user_id = $ilUser->getId();
6129 
6130  // code is obligatory?
6131  if(!$this->isAccessibleWithoutCode())
6132  {
6133  if(!$a_code)
6134  {
6135  // registered raters do not need code
6136  if($this->get360Mode() &&
6137  $user_id != ANONYMOUS_USER_ID &&
6138  $this->isRater(0, $user_id))
6139  {
6140  // auto-generate code
6141  $a_code = $this->createNewAccessCode();
6142  $this->saveUserAccessCode($user_id, $a_code);
6143  }
6144  else
6145  {
6146  return null;
6147  }
6148  }
6149  }
6150  else if($user_id == ANONYMOUS_USER_ID ||
6151  $this->getAnonymize() == self::ANONYMIZE_FREEACCESS)
6152  {
6153  if(!$a_code)
6154  {
6155  // auto-generate code
6156  $a_code = $this->createNewAccessCode();
6157  $this->saveUserAccessCode($user_id, $a_code);
6158  }
6159  }
6160  else
6161  {
6162  $a_code = null;
6163  }
6164 
6165  $res = array();
6166 
6167  $sql = "SELECT * FROM svy_finished".
6168  " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer");
6169  // if proper user id is given, use it or current code
6170  if($user_id != ANONYMOUS_USER_ID)
6171  {
6172  $sql .= " AND (user_fi = ".$ilDB->quote($user_id, "integer").
6173  " OR anonymous_id = ".$ilDB->quote($a_code, "text").")";
6174  }
6175  // use anonymous code to find finished id(s)
6176  else
6177  {
6178  $sql .= " AND anonymous_id = ".$ilDB->quote($a_code, "text");
6179  }
6180  $set = $ilDB->query($sql);
6181  while($row = $ilDB->fetchAssoc($set))
6182  {
6183  $res[$row["finished_id"]] = array("appr_id" => $row["appr_id"],
6184  "user_id" => $row["user_fi"],
6185  "code" => $row["anonymous_id"],
6186  "finished" => (bool)$row["state"]);
6187  }
6188 
6189  return array("code"=>$a_code, "runs"=>$res);
6190  }
6191 
6192  function findCodeForUser($a_user_id)
6193  {
6194  global $ilDB;
6195 
6196  if($a_user_id != ANONYMOUS_USER_ID)
6197  {
6198  $set = $ilDB->query("SELECT sf.anonymous_id FROM svy_finished sf".
6199  " WHERE sf.survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer").
6200  " AND sf.user_fi = ".$ilDB->quote($a_user_id, "integer"));
6201  $a_code = $ilDB->fetchAssoc($set);
6202  return $a_code["anonymous_id"];
6203  }
6204  }
6205 
6206  function isUnusedCode($a_code, $a_user_id)
6207  {
6208  global $ilDB;
6209 
6210  $set = $ilDB->query("SELECT user_fi FROM svy_finished".
6211  " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer").
6212  " AND anonymous_id = ".$ilDB->quote($a_code, "text"));
6213  $user_id = $ilDB->fetchAssoc($set);
6214  $user_id = $user_id["user_fi"];
6215 
6216  if($user_id && ($user_id != $a_user_id || $user_id == ANONYMOUS_USER_ID))
6217  {
6218  return false;
6219  }
6220  return true;
6221  }
6222 
6223  function getFinishedIdsForAppraiseeId($a_appr_id, $a_exclude_appraisee = false)
6224  {
6225  global $ilDB;
6226 
6227  $res = array();
6228 
6229  $set = $ilDB->query("SELECT finished_id, user_fi FROM svy_finished".
6230  " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer").
6231  " AND appr_id = ".$ilDB->quote($a_appr_id, "integer"));
6232  while($row = $ilDB->fetchAssoc($set))
6233  {
6234  if ($a_exclude_appraisee && $row["user_fi"] == $a_appr_id)
6235  {
6236  continue;
6237  }
6238  $res[] = $row["finished_id"];
6239  }
6240 
6241  return $res;
6242  }
6243 
6251  function getFinishedIdForAppraiseeIdAndRaterId($a_appr_id, $a_rat_id)
6252  {
6253  global $ilDB;
6254 
6255  $set = $ilDB->query("SELECT finished_id, user_fi FROM svy_finished".
6256  " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer").
6257  " AND appr_id = ".$ilDB->quote($a_appr_id, "integer").
6258  " AND user_fi = ".$ilDB->quote($a_rat_id, "integer"));
6259  $row = $ilDB->fetchAssoc($set);
6260  return $row["finished_id"];
6261  }
6262 
6263 
6264  // 360° using competence/skill service
6265 
6271  function set360SkillService($a_val)
6272  {
6273  $this->mode_360_skill_service = $a_val;
6274  }
6275 
6282  {
6284  }
6285 
6286  function set360RaterSent($a_appraisee_id, $a_user_id, $a_anonymous_id, $a_tstamp = null)
6287  {
6288  global $ilDB;
6289 
6290  if(!$a_tstamp)
6291  {
6292  $a_tstamp = time();
6293  }
6294 
6295  $ilDB->manipulate("UPDATE svy_360_rater".
6296  " SET mail_sent = ".$ilDB->quote($a_tstamp, "integer").
6297  " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer").
6298  " AND appr_id = ".$ilDB->quote($a_appraisee_id, "integer").
6299  " AND user_id = ".$ilDB->quote($a_user_id, "integer").
6300  " AND anonymous_id = ".$ilDB->quote($a_anonymous_id, "integer"));
6301  }
6302 
6303  function closeAppraisee($a_user_id)
6304  {
6305  global $ilDB;
6306 
6307  // close the appraisee
6308  $ilDB->manipulate("UPDATE svy_360_appr".
6309  " SET has_closed = ".$ilDB->quote(time(), "integer").
6310  " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer").
6311  " AND user_id = ".$ilDB->quote($a_user_id, "integer"));
6312 
6313  // write competences
6314  include_once("./Services/Skill/classes/class.ilSkillManagementSettings.php");
6315  $skmg_set = new ilSkillManagementSettings();
6316  if ($this->get360SkillService() && $skmg_set->isActivated())
6317  {
6318  include_once("./Modules/Survey/classes/class.ilSurveySkill.php");
6319  $sskill = new ilSurveySkill($this);
6320  $sskill->writeAppraiseeSkills($a_user_id);
6321  }
6322  }
6323 
6325  {
6326  global $ilDB;
6327 
6328  $ilDB->manipulate("UPDATE svy_360_appr".
6329  " SET has_closed = ".$ilDB->quote(null, "integer").
6330  " WHERE obj_id = ".$ilDB->quote($this->getSurveyId(), "integer"));
6331  }
6332 
6333  public static function validateExternalRaterCode($a_ref_id, $a_code)
6334  {
6335  if(!isset($_SESSION["360_extrtr"][$a_ref_id]))
6336  {
6337  $svy = new self($a_ref_id);
6338  $svy->loadFromDB();
6339 
6340  if($svy->canStartSurvey(null, true) &&
6341  $svy->get360Mode() &&
6342  $svy->isAnonymousKey($a_code))
6343  {
6344  $anonymous_id = $svy->getAnonymousIdByCode($a_code);
6345  if($anonymous_id)
6346  {
6347  if(sizeof($svy->getAppraiseesToRate(null, $anonymous_id)))
6348  {
6349  $_SESSION["360_extrtr"][$a_ref_id] = true;
6350  return true;
6351  }
6352  }
6353  }
6354 
6355  $_SESSION["360_extrtr"][$a_ref_id] = false;
6356  return false;
6357  }
6358 
6359  return $_SESSION["360_extrtr"][$a_ref_id];
6360  }
6361 
6362 
6363  //
6364  // reminder/notification
6365  //
6366 
6367  public function getReminderStatus()
6368  {
6369  return (bool)$this->reminder_status;
6370  }
6371 
6372  public function setReminderStatus($a_value)
6373  {
6374  $this->reminder_status = (bool)$a_value;
6375  }
6376 
6377  public function getReminderStart()
6378  {
6379  return $this->reminder_start;
6380  }
6381 
6382  public function setReminderStart(ilDate $a_value = null)
6383  {
6384  $this->reminder_start = $a_value;
6385  }
6386 
6387  public function getReminderEnd()
6388  {
6389  return $this->reminder_end;
6390  }
6391 
6392  public function setReminderEnd(ilDate $a_value = null)
6393  {
6394  $this->reminder_end = $a_value;
6395  }
6396 
6397  public function getReminderFrequency()
6398  {
6400  }
6401 
6402  public function setReminderFrequency($a_value)
6403  {
6404  $this->reminder_frequency = (int)$a_value;
6405  }
6406 
6407  public function getReminderTarget()
6408  {
6409  return $this->reminder_target;
6410  }
6411 
6412  public function setReminderTarget($a_value)
6413  {
6414  $this->reminder_target = (int)$a_value;
6415  }
6416 
6417  public function getReminderLastSent()
6418  {
6420  }
6421 
6422  public function setReminderLastSent($a_value)
6423  {
6424  $this->reminder_last_sent = $a_value;
6425  }
6426 
6427  public function getTutorNotificationStatus()
6428  {
6429  return (bool)$this->tutor_ntf_status;
6430  }
6431 
6432  public function setTutorNotificationStatus($a_value)
6433  {
6434  $this->tutor_ntf_status = (bool)$a_value;
6435  }
6436 
6438  {
6440  }
6441 
6442  public function setTutorNotificationRecipients(array $a_value)
6443  {
6444  $this->tutor_ntf_recipients = $a_value;
6445  }
6446 
6447  public function getTutorNotificationTarget()
6448  {
6449  return $this->tutor_ntf_target;
6450  }
6451 
6452  public function setTutorNotificationTarget($a_value)
6453  {
6454  $this->tutor_ntf_target = (int)$a_value;
6455  }
6456 
6457  protected function checkTutorNotification()
6458  {
6459  global $ilDB;
6460 
6461  if($this->getTutorNotificationStatus())
6462  {
6463  $user_ids = $this->getNotificationTargetUserIds(($this->getTutorNotificationTarget() == self::NOTIFICATION_INVITED_USERS));
6464  if($user_ids)
6465  {
6466  $set = $ilDB->query("SELECT COUNT(*) numall FROM svy_finished".
6467  " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer").
6468  " AND state = ".$ilDB->quote(1, "integer").
6469  " AND ".$ilDB->in("user_fi", $user_ids, "", "integer"));
6470  $row = $ilDB->fetchAssoc($set);
6471  if($row["numall"] == sizeof($user_ids))
6472  {
6473  $this->sendTutorNotification();
6474  }
6475  }
6476  }
6477  }
6478 
6479  public function getNotificationTargetUserIds($a_use_invited)
6480  {
6481  global $tree;
6482 
6483  if((bool)$a_use_invited)
6484  {
6485  $user_ids = $this->getInvitedUsers();
6486  }
6487  else
6488  {
6489  $parent_grp_ref_id = $tree->checkForParentType($this->getRefId(), "grp");
6490  if($parent_grp_ref_id)
6491  {
6492  include_once "Modules/Group/classes/class.ilGroupParticipants.php";
6493  $part = new ilGroupParticipants(ilObject::_lookupObjId($parent_grp_ref_id));
6494  $user_ids = $part->getMembers();
6495  }
6496  else
6497  {
6498  $parent_crs_ref_id = $tree->checkForParentType($this->getRefId(), "crs");
6499  if($parent_crs_ref_id)
6500  {
6501  include_once "Modules/Course/classes/class.ilCourseParticipants.php";
6502  $part = new ilCourseParticipants(ilObject::_lookupObjId($parent_crs_ref_id));
6503  $user_ids = $part->getMembers();
6504  }
6505  }
6506  }
6507  return $user_ids;
6508  }
6509 
6510  protected function sendTutorNotification()
6511  {
6512  include_once "./Services/Mail/classes/class.ilMail.php";
6513  include_once "./Services/User/classes/class.ilObjUser.php";
6514  include_once "./Services/Language/classes/class.ilLanguageFactory.php";
6515  include_once "./Services/User/classes/class.ilUserUtil.php";
6516  include_once "./Services/Link/classes/class.ilLink.php";
6517  $link = ilLink::_getStaticLink($this->getRefId(), "svy");
6518 
6519  foreach($this->getTutorNotificationRecipients() as $user_id)
6520  {
6521  // use language of recipient to compose message
6522  $ulng = ilLanguageFactory::_getLanguageOfUser($user_id);
6523  $ulng->loadLanguageModule('survey');
6524 
6525  $subject = sprintf($ulng->txt('survey_notification_tutor_subject'), $this->getTitle());
6526  $message = sprintf($ulng->txt('survey_notification_tutor_salutation'), ilObjUser::_lookupFullname($user_id))."\n\n";
6527 
6528  $message .= $ulng->txt('survey_notification_tutor_body').":\n\n";
6529  $message .= $ulng->txt('obj_svy').": ". $this->getTitle()."\n";
6530  $message .= "\n".$ulng->txt('survey_notification_tutor_link').": ".$link;
6531 
6532  $mail_obj = new ilMail(ANONYMOUS_USER_ID);
6533  $mail_obj->appendInstallationSignature(true);
6534  $mail_obj->sendMail(ilObjUser::_lookupLogin($user_id),
6535  "", "", $subject, $message, array(), array("system"));
6536  }
6537  }
6538 
6539  public function checkReminder()
6540  {
6541  global $ilDB, $ilAccess;
6542 
6543  $now = time();
6544  $now_with_format = date("YmdHis", $now);
6545  $today = date("Y-m-d");
6546 
6547  // object settings / participation period
6548  if($this->isOffline() ||
6549  !$this->getReminderStatus() ||
6550  ($this->getStartDate() && $now_with_format < $this->getStartDate()) ||
6551  ($this->getEndDate() && $now_with_format > $this->getEndDate()))
6552  {
6553  return false;
6554  }
6555 
6556  // reminder period
6557  $start = $this->getReminderStart();
6558  if($start)
6559  {
6560  $start = $start->get(IL_CAL_DATE);
6561  }
6562  $end = $this->getReminderEnd();
6563  if($end)
6564  {
6565  $end = $end->get(IL_CAL_DATE);
6566  }
6567  if($today < $start ||
6568  ($end && $today > $end))
6569  {
6570  return false;
6571  }
6572 
6573  // object access period
6574  include_once "Services/Object/classes/class.ilObjectActivation.php";
6575  $item_data = ilObjectActivation::getItem($this->getRefId());
6576  if($item_data["timing_type"] == ilObjectActivation::TIMINGS_ACTIVATION &&
6577  ($now < $item_data["timing_start"] ||
6578  $now > $item_data["timing_end"]))
6579  {
6580  return false;
6581  }
6582 
6583  // check frequency
6584  $cut = new ilDate($today, IL_CAL_DATE);
6585  $cut->increment(IL_CAL_DAY, $this->getReminderFrequency()*-1);
6586  if(!$this->getReminderLastSent() ||
6587  $cut->get(IL_CAL_DATE) >= substr($this->getReminderLastSent(), 0, 10))
6588  {
6589  $missing_ids = array();
6590 
6591  // #16871
6592  $user_ids = $this->getNotificationTargetUserIds(($this->getReminderTarget() == self::NOTIFICATION_INVITED_USERS));
6593  if($user_ids)
6594  {
6595  // gather participants who already finished
6596  $finished_ids = array();
6597  $set = $ilDB->query("SELECT user_fi FROM svy_finished".
6598  " WHERE survey_fi = ".$ilDB->quote($this->getSurveyId(), "integer").
6599  " AND state = ".$ilDB->quote(1, "text").
6600  " AND ".$ilDB->in("user_fi", $user_ids, "", "integer"));
6601  while($row = $ilDB->fetchAssoc($set))
6602  {
6603  $finished_ids[] = $row["user_fi"];
6604  }
6605 
6606  // some users missing out?
6607  $missing_ids = array_diff($user_ids, $finished_ids);
6608  if($missing_ids)
6609  {
6610  foreach($missing_ids as $idx => $user_id)
6611  {
6612  // should be able to participate
6613  if(!$ilAccess->checkAccessOfUser($user_id, "read", "", $this->getRefId(), "svy", $this->getId()))
6614  {
6615  unset($missing_ids[$idx]);
6616  }
6617  }
6618  }
6619  if($missing_ids)
6620  {
6621  $this->sentReminder($missing_ids);
6622  }
6623  }
6624 
6625  $this->setReminderLastSent($today);
6626  $this->saveToDb();
6627 
6628  return sizeof($missing_ids);
6629  }
6630 
6631  return false;
6632  }
6633 
6634  protected function sentReminder(array $a_recipient_ids)
6635  {
6636  include_once "./Services/Mail/classes/class.ilMail.php";
6637  include_once "./Services/User/classes/class.ilObjUser.php";
6638  include_once "./Services/Language/classes/class.ilLanguageFactory.php";
6639  include_once "./Services/User/classes/class.ilUserUtil.php";
6640  include_once "./Services/Link/classes/class.ilLink.php";
6641  $link = ilLink::_getStaticLink($this->getRefId(), "svy");
6642 
6643  foreach($a_recipient_ids as $user_id)
6644  {
6645  // use language of recipient to compose message
6646  $ulng = ilLanguageFactory::_getLanguageOfUser($user_id);
6647  $ulng->loadLanguageModule('survey');
6648 
6649  $subject = sprintf($ulng->txt('survey_reminder_subject'), $this->getTitle());
6650  $message = sprintf($ulng->txt('survey_reminder_salutation'), ilObjUser::_lookupFullname($user_id))."\n\n";
6651 
6652  $message .= $ulng->txt('survey_reminder_body').":\n\n";
6653  $message .= $ulng->txt('obj_svy').": ". $this->getTitle()."\n";
6654  $message .= "\n".$ulng->txt('survey_reminder_link').": ".$link;
6655 
6656  $mail_obj = new ilMail(ANONYMOUS_USER_ID);
6657  $mail_obj->appendInstallationSignature(true);
6658  $mail_obj->sendMail(ilObjUser::_lookupLogin($user_id),
6659  "", "", $subject, $message, array(), array("system"));
6660  }
6661  }
6662 
6663  function setActivationStartDate($starting_time = NULL)
6664  {
6665  $this->activation_starting_time = $starting_time;
6666  }
6667 
6668  function setActivationEndDate($ending_time = NULL)
6669  {
6670  $this->activation_ending_time = $ending_time;
6671  }
6672 
6674  {
6675  return (strlen($this->activation_starting_time)) ? $this->activation_starting_time : NULL;
6676  }
6677 
6679  {
6680  return (strlen($this->activation_ending_time)) ? $this->activation_ending_time : NULL;
6681  }
6682 
6683  function setViewOwnResults($a_value)
6684  {
6685  $this->view_own_results = (bool)$a_value;
6686  }
6687 
6689  {
6690  return $this->view_own_results;
6691  }
6692 
6693  function setMailOwnResults($a_value)
6694  {
6695  $this->mail_own_results = (bool)$a_value;
6696  }
6697 
6699  {
6700  return $this->mail_own_results;
6701  }
6702 
6703  public static function getSurveySkippedValue()
6704  {
6705  global $lng;
6706 
6707  // #13541
6708 
6709  include_once "./Services/Administration/classes/class.ilSetting.php";
6710  $surveySetting = new ilSetting("survey");
6711  if(!$surveySetting->get("skipped_is_custom", false))
6712  {
6713  return $lng->txt("skipped");
6714  }
6715  else
6716  {
6717  return $surveySetting->get("skipped_custom_value", "");
6718  }
6719  }
6720 
6721 } // END class.ilObjSurvey
6722 
6723 ?>
createSurveyCodes($nrOfCodes)
showQuestionTitles()
Sets the question titles visible during the query.
sendNotificationMail($user_id, $anonymize_id, $appr_id)
static _lookupLogin($a_user_id)
lookup login
static _lookupName($a_user_id)
lookup user name
xslt_create()
set360RaterSent($a_appraisee_id, $a_user_id, $a_anonymous_id, $a_tstamp=null)
static makeDirParents($a_dir)
Create a new directory and all parent directories.
deliverPDFfromFO($fo)
Delivers a PDF file from a XSL-FO string.
_hasDatasets($survey_id)
ILIAS Setting Class.
setInvitationAndMode($invitation=0, $invitation_mode=0)
Sets the invitation status and mode (a more performant solution if you change both) ...
static deliverData($a_data, $a_filename, $mime="application/octet-stream", $charset="")
deliver data for download via browser.
print $file
getAppraiseesToRate($a_user_id, $a_anonymous_id=null)
getUserSurveyExecutionStatus($a_code=null)
createNewAccessCode()
Returns a new, unused survey access code.
updateConjunctionForQuestions($questions, $conjunction)
is360SurveyStarted($appr_id, $user_id, $anonymous_code=null)
_getQuestionblock($questionblock_id)
Returns the database row for a given question block.
$size
Definition: RandomTest.php:79
read($a_force_db=false)
read object data from db into object
setEndDateAndTime($end_date="", $end_time)
Sets the end date of the survey.
isAnonymizedParticipant($key)
& getSurveyPages()
Returns the survey pages in an array (a page contains one or more questions)
$separator
deleteRater($a_appraisee_id, $a_user_id, $a_anonymous_id=0)
const IL_CAL_DATETIME
static prepareTextareaOutput($txt_output, $prepare_for_latex_output=FALSE, $omitNl2BrWhenTextArea=false)
Prepares a string for a text area output where latex code may be in it If the text is HTML-free...
& getEvaluationByUser($questions, $active_id)
Calculates the evaluation data for a given user or anonymous id.
processPrintoutput2FO($print_output)
Convert a print output to XSL-FO.
isAllowedToTakeMultipleSurveys($userid="")
Checks if a user is allowed to take multiple survey.
setReminderLastSent($a_value)
$_SESSION["AccountId"]
$result
set360Results($a_value)
const EVALUATION_ACCESS_OFF
getParticipantTextResults($active_id)
applySettingsTemplate($template_id)
Apply settings template.
& getSurveyFinishedIds()
Get the finished id&#39;s of all survey participants.
getQuestionGUI($questiontype, $question_id)
Returns a question gui object to a given questiontype and question id.
static validateExternalRaterCode($a_ref_id, $a_code)
setMailNotification($a_notification)
& _getUsedHTMLTagsAsString($a_module="")
Returns a string of all allowed HTML tags for text editing.
disinviteAllUsers()
Disinvite all users.
saveUserSettings($usr_id, $key, $title, $value)
getConstraints($question_id)
Returns the constraints to a given question or questionblock.
const EVALUATION_ACCESS_PARTICIPANTS
$_GET["client_id"]
isOffline()
Gets the survey status.
setTutorNotificationTarget($a_value)
$h
static getSurveySkippedValue()
getQuestionblock($questionblock_id)
Returns the database row for a given question block.
deleteSurveyCode($survey_code)
Deletes a given survey access code.
getWorkingtimeForParticipant($finished_id)
getSurveyId()
Returns the survey database id.
updateMetaData()
update meta data entry
xslt_free(&$proc)
getSurveyCodesForExport(array $a_codes=null, array $a_ids=null)
Returns a list of survey codes for file export.
$code
Definition: example_050.php:99
& getSurveyParticipants($finished_ids=null)
isComplete()
Returns 1, if a survey is complete for use.
removeQuestions($remove_questions, $remove_questionblocks)
Remove questions from the survey.
getAnonymousIdByCode($a_code)
Class ilObject Basic functions for all objects.
isAccessibleWithoutCode()
Checks if the survey is accessable without a survey code.
canStartSurvey($anonymous_id=NULL, $a_no_rbac=false)
Checks if the survey can be started.
setReminderFrequency($a_value)
removeQuestion($question_id)
Remove a question from the survey.
static getItem($a_ref_id)
Get item data.
static _getObjectsByOperations($a_obj_type, $a_operation, $a_usr_id=0, $limit=0)
Get all objects of a specific type and check access This function is not recursive, instead it parses the serialized rbac_pa entries.
deleteConstraint($constraint_id)
Deletes a constraint of a question.
setAuthor($author="")
Sets the authors name of the ilObjSurvey object.
isOnline()
Gets the survey status.
static is_email($a_email)
This preg-based function checks whether an e-mail address is formally valid.
static unzip($a_file, $overwrite=false, $a_flat=false)
unzip file
static _includeClass($question_type, $gui=0)
Include the php class file for a given question type.
XML writer class.
prepareTextareaOutput($txt_output)
Prepares a string for a text area output in surveys.
setPoolUsage($a_value)
& getVariables($question_id)
Returns all variables of a question.
locateImportFiles($a_dir)
Locates the import directory and the xml file in a directory with an unzipped import file...
set360Mode($a_value)
getIntroduction()
Gets the introduction text.
unfoldQuestionblocks($questionblocks)
Unfolds question blocks of a question pool.
static _lookupTitle($a_id)
lookup object title
create($a_upload=false)
create survey object
getAnonymize()
get anonymize status
setViewOwnResults($a_value)
getUserAccessCode($user_id)
Returns a survey access code that was saved for a registered user.
closeAppraisee($a_user_id)
bindSurveyCodeToUser($user_id, $code)
moveUpQuestionblock($questionblock_id)
Moves a questionblock up in the list of survey questions.
$url
Definition: shib_logout.php:72
setTutorNotificationStatus($a_value)
Survey Question Import Parser.
_addQuestionblock($title="", $owner=0, $show_questiontext=true, $show_blocktitle=false)
Adds a questionblock to the database.
setObligatoryStates($obligatory_questions)
Sets the obligatory states for questions in a survey from the questions form.
const IL_CAL_UNIX
_cleanupMediaObjectUsage($a_text, $a_usage_type, $a_usage_id)
synchronises appearances of media objects in $a_text with media object usage table ...
getOwner()
get object owner
set360SkillService($a_val)
Set skill service.
static sortArray($array, $a_array_sortby, $a_array_sortorder=0, $a_numeric=false, $a_keep_keys=false)
sortArray
static getASCIIFilename($a_filename)
convert utf8 to ascii filename
static _replaceMediaObjectImageSrc($a_text, $a_direction=0, $nic=IL_INST_ID)
replaces image source from mob image urls with the mob id or replaces mob id with the correct image s...
const INVITATION_ON
canExportSurveyCode()
Checks if the survey code can be exported with the survey evaluation.
_removeUsage($a_mob_id, $a_type, $a_id, $a_usage_hist_nr=0, $a_lang="-")
Remove usage of mob in another container.
getAllRelations($short_as_key=false)
Returns all available relations.
& getQuestionblockQuestions($questionblock_id)
Returns the question titles of all questions of a question block.
inviteRole($role_id)
Invites a role to a survey.
addRater($a_appraisee_id, $a_user_id, $a_anonymous_id=0)
_lookupFullname($a_user_id)
Lookup Full Name.
& processCSVRow($row, $quoteAll=FALSE, $separator=";")
Processes an array as a CSV row and converts the array values to correct CSV values.
setMailAddresses($a_addresses)
removeQuestionFromBlock($question_id, $questionblock_id)
getSurveyCodesTableData(array $ids=null, $lang=null)
Fetches the data for the survey codes table.
Skill/Competence handling in surveys.
removeConstraintsConcerningQuestion($question_id)
Remove constraints concerning a question with a given question_id.
insertQuestion($question_id)
Inserts a question in the survey and saves the relation to the database.
moveUpQuestion($question_id)
Moves a question up in the list of survey questions.
getInvitationMode()
Gets the invitation mode.
removeSelectedSurveyResults($finished_ids)
Deletes the user data of a given array of survey participants.
getEndDate()
Gets the end date of the survey.
insertQuestionblock($questionblock_id)
Inserts a questionblock in the survey and saves the relation to the database.
setStartTime($finished_id, $first_question)
setReminderEnd(ilDate $a_value=null)
xslt_error(&$proc)
& getUserSpecificResults($finished_ids)
Calculates the evaluation data for the user specific results.
getAuthor()
Gets the authors name of the ilObjSurvey object.
isHTML($a_text)
Checks if a given string contains HTML or not.
hideQuestionTitles()
Sets the question titles hidden during the query.
saveQuestionsToDb()
Saves the survey questions to the database.
duplicateQuestionForSurvey($question_id, $a_force=false)
Takes a question and creates a copy of the question for use in the survey.
const IL_CAL_DAY
cloneObject($a_target_id, $a_copy_id=0)
Clone object.
deleteSurveyRecord()
Deletes the survey from the database.
updateConstraint($precondition_id, $if_question_id, $relation, $value, $conjunction)
Updates a precondition.
static getNamePresentation($a_user_id, $a_user_image=false, $a_profile_link=false, $a_profile_back_link="", $a_force_first_lastname=false, $a_omit_login=false, $a_sortable=true, $a_return_data_array=false)
Default behaviour is:
isPluginActive($a_pname)
Checks whether or not a question plugin with a given name is active.
disinviteUser($user_id)
Disinvites a user from a survey.
_saveUsage($a_mob_id, $a_type, $a_id, $a_usage_hist_nr=0, $a_lang="-")
Save usage of mob within another container (e.g.
getSurveyCodesCount()
Returns the number of generated survey codes for the survey.
static _getInstance($a_copy_id)
Get instance of copy wizard options.
$data
hasAnonymizedResults()
Checks if the survey results are to be anonymized.
isAppraisee($a_user_id)
setInvitationMode($invitation_mode=0)
Sets the invitation mode.
inviteUser($user_id)
Invites a user to a survey.
getNextPage($active_page_question_id, $direction)
Returns the next "page" of a running test.
Class for single dates.
$y
Definition: example_007.php:83
setReminderTarget($a_value)
getLastActivePage($active_id)
Returns the question id of the last active page a user visited in a survey.
& getSurveyQuestions($with_answers=false)
Returns the survey questions and questionblocks in an array.
$mobs
_getLastAccess($finished_id)
getId()
get object id public
const ANONYMIZE_FREEACCESS
set360SelfEvaluation($a_value)
isUnusedCode($a_code, $a_user_id)
setShowQuestionTitles($a_show)
Sets the status of the display_question_titles attribute.
loadFromDb()
Loads a survey object from a database.
setActivationLimited($a_value)
setInvitation($invitation=0)
Sets the invitation status.
addMaterialTag(&$a_xml_writer, $a_material, $close_material_tag=TRUE, $add_mobs=TRUE, $attribs=NULL)
Creates an XML material tag from a plain text or xhtml text.
const NOTIFICATION_PARENT_COURSE
setMailParticipantData($a_data)
static _saveTempFileAsMediaObject($name, $tmp_name, $upload=TRUE)
Create new media object and update page in db and return new media object.
setActivationStartDate($starting_time=NULL)
& getObligatoryStates()
Gets specific obligatory states of the survey.
static _lookupDescription($a_id)
lookup object description
getFinishedIdsForAppraiseeId($a_appr_id, $a_exclude_appraisee=false)
Class Mail this class handles base functions for mail handling.
updateCode($a_id, $a_email, $a_last_name, $a_first_name, $a_sent)
notify($a_event, $a_ref_id, $a_parent_non_rbac_id, $a_node_id, $a_params=0)
notifys an object about an event occured Based on the event happend, each object may decide how it re...
static moveUploadedFile($a_file, $a_name, $a_target, $a_raise_errors=true, $a_mode="move_uploaded")
move uploaded file
updateOrder(array $a_order)
getEvaluationAccess()
Gets the learners evaluation access.
static _lookupObjId($a_id)
setActivationVisibility($a_value)
addQuestion($question_id)
Adds a question to the survey.
const QUESTIONTITLES_VISIBLE
getImportDirectory()
get import directory of survey
getQuestionblocksTable($arrFilter)
Calculates the data for the output of the questionblock browser.
const QUESTIONTITLES_HIDDEN
static & _getQuestionGUI($questiontype, $question_id=-1)
Creates a question gui representation.
& getQuestions($question_ids)
getQuestionType($question_id)
Returns the question type of a question with a given id.
setMailOwnResults($a_value)
setReminderStart(ilDate $a_value=null)
static formatDate(ilDateTime $date)
Format a date public.
setTutorNotificationRecipients(array $a_value)
setStatus($status=self::STATUS_OFFLINE)
Sets the survey status.
setIntroduction($introduction="")
Sets the introduction text.
getTitle()
get object title public
ilObjSurvey($a_id=0, $a_call_by_reference=true)
Constructor public.
static _dropDesktopItem($a_usr_id, $a_item_id, $a_type)
drop an item from user&#39;s personal desktop
getDescription()
get object description
const IL_COMP_MODULE
Date and time handling
set360SelfRaters($a_value)
getShowQuestionTitles()
Gets the status of the display_question_titles attribute.
redirection script todo: (a better solution should control the processing via a xml file) ...
cloneMetaData($target_obj)
Copy meta data.
toXML()
Returns a QTI xml representation of the survey.
xmlHeader()
Writes xml header public.
& getInvitedUsers()
Returns a list of all invited users in a survey.
addConstraintToQuestion($to_question_id, $constraint_id)
Adds a constraint to a question.
importSurveyCode($a_anonymize_key, $a_created, $a_data)
Class ilObjMediaObject.
const MODE_PREDEFINED_USERS
_lookupEmail($a_user_id)
Lookup email.
getUserDataFromActiveId($active_id)
Returns the user information from an active_id (survey_finished.finished_id)
setSurveyId($survey_id)
Sets the survey id.
static stripSlashes($a_str, $a_strip_html=true, $a_allow="")
strip slashes if magic qoutes is enabled
createQuestionblock($title, $show_questiontext, $show_blocktitle, $questions)
Creates a question block for the survey.
const NOTIFICATION_INVITED_USERS
getInvitation()
Gets the invitation status.
getExportDirectory()
get export directory of survey
fillSurveyForUser($user_id=ANONYMOUS_USER_ID)
Fills a survey randomly with data for a given user.
setReminderStatus($a_value)
setPage($finished_id, $page_id)
Sets the number of the active survey page.
getType()
get object type public
getNotificationTargetUserIds($a_use_invited)
const INVITATION_OFF
setEvaluationAccess($evaluation_access=self::EVALUATION_ACCESS_OFF)
Sets the learners evaluation access.
createImportDirectory()
creates data directory for import files (data_dir/svy_data/svy_<id>/import, depending on data directo...
& getQuestionpoolTitles($could_be_offline=FALSE, $showPath=FALSE)
Get the titles of all available survey question pools.
createExportDirectory()
creates data directory for export files (data_dir/svy_data/svy_<id>/export, depending on data directo...
setTimingType($a_type)
Set timing type.
_getMobsOfObject($a_type, $a_id, $a_usage_hist_nr=0, $a_lang="-")
get mobs of object
static makeDir($a_dir)
creates a new directory and inherits all filesystem permissions of the parent directory You may pass ...
setEndDate($end_date="")
Sets the end date of the survey.
static _getLanguageOfUser($a_usr_id)
Get language object of user.
& getUserData($ids)
Returns a data of all users specified by id list.
getStatus()
Gets the survey status.
finishSurvey($finished_id)
Finishes the survey creating an entry in the database.
const EVALUATION_ACCESS_ALL
& _getGlobalSurveyData($obj_id)
Returns an array with data needed in the repository, personal desktop or courses. ...
getFinishedIdForAppraiseeIdAndRaterId($a_appr_id, $a_rat_id)
Get finished id for an appraisee and a rater.
deleteWorkingData($question_id, $active_id)
Deletes the working data of a question in the database.
static factory($a_package)
Create an XML_RPC2 client instance.
saveCompletionStatus()
Saves the completion status of the survey.
_getOriginalId($question_id, $a_return_question_id_if_no_original=true)
Returns the original id of a question.
static ilTempnam($a_temp_path=null)
Create a temporary file in an ILIAS writable directory.
setEndTime($finished_id)
getExternalCodeRecipients($a_check_finished=false)
getStartDate()
Gets the start date of the survey.
checkConstraint($constraint_data, $working_data)
Checks if a constraint is valid.
static _addDesktopItem($a_usr_id, $a_item_id, $a_type, $a_par="")
add an item to user&#39;s personal desktop
getAllRTEContent()
Returns the content of all RTE enabled text areas in the test.
createSurveyCodesForExternalData($data)
const IL_CAL_DATE
saveUserAccessCode($user_id, $access_code)
Saves a survey access code for a registered user to the database.
cloneTextblocks($mapping)
Clones the textblocks of survey questions.
saveToDb()
Saves a survey object to a database.
$messages
Definition: en-x-test.php:7
static getDataDir()
get data directory (outside webspace)
createMetaData()
Create meta data entry.
& getExistingQuestions()
Gets the question id&#39;s of the questions which are already in the survey.
global $ilUser
Definition: imgupload.php:15
_getQuestionType($question_id)
Returns the question type of a question with a given id.
getQuestionsTable($arrFilter)
Calculates the data for the output of the question browser.
saveHeading($heading="", $insertbefore)
getCumulatedResults(&$question, $finished_ids)
Calculates the evaluation data for a question.
getRatersData($a_appraisee_id)
isRater($a_appraisee_id, $a_user_id, $a_anonymous_id=0)
update()
update object data
addAppraisee($a_user_id)
setStartDateAndTime($start_date="", $start_time)
Sets the start date of the survey.
addConstraint($if_question_id, $relation, $value, $conjunction)
Adds a constraint.
global $ilDB
setActivationEndDate($ending_time=NULL)
saveAuthorToMetadata($a_author="")
Saves an authors name into the lifecycle metadata if no lifecycle metadata exists This will only be c...
& getAvailableQuestionpools($use_obj_id=false, $could_be_offline=false, $showPath=FALSE, $permission="read")
Returns the available question pools for the active user.
getRefId()
get reference id public
$text
getAnonymousId($id)
Checks for an anomyous survey id in the database an returns the id.
countReferences()
count references of object
Class ilObjGroup.
deleteMetaData()
delete meta data entry
get360SkillService()
Get skill service.
moveDownQuestion($question_id)
Moves a question down in the list of survey questions.
getTextblock($question_id)
findCodeForUser($a_user_id)
getActiveID($user_id, $anonymize_id, $appr_id)
Checks if a user already started a survey.
setTemplate($template_id)
getOutro()
Gets the outro text.
getUserSettings($usr_id, $key)
const IL_CAL_TIMESTAMP
sentReminder(array $a_recipient_ids)
$GLOBALS['PHPCAS_CLIENT']
This global variable is used by the interface class phpCAS.
Definition: CAS.php:276
set360SelfAppraisee($a_value)
const ANONYMIZE_CODE_ALL
getUserSurveyCode($user_id)
sendCodes($not_sent, $subject, $message, $lang)
_isComplete($obj_id)
Returns 1, if a survey is complete for use.
modifyQuestionblock($questionblock_id, $title, $show_questiontext, $show_blocktitle)
Modifies a question block.
Class ilInvalidSurveyImportFileException.
_getNrOfParticipants($survey_id)
Returns the number of participants for a survey.
moveQuestions($move_questions, $target_index, $insert_mode)
Move questions and/or questionblocks to another position.
& _instanciateQuestion($question_id)
Creates an instance of a question with a given question id.
isPoolActive()
Get current pool status.
_isComplete($question_id)
Checks whether the question is complete or not.
loadWorkingData($question_id, $active_id)
Gets the working data of question from the database.
setStartDate($start_date="")
Sets the start date of the survey.
static getInstance($a_obj_id)
static delDir($a_dir, $a_clean_only=false)
removes a dir and all its content (subdirs and files) recursively
deleteConstraints($question_id)
Deletes the constraints for a question.
importObject($file_info, $svy_qpl_id)
Imports a survey from XML into the ILIAS database.
Class ilObjectActivation.
static _getUserData($a_internalids)
return user data for given user ids
_getConstraints($survey_id)
Returns the constraints to a given question or questionblock.
& _instanciateQuestion($question_id)
Creates an instance of a question with a given question id.
Wrapper classes for system notifications.
getDetailedParticipantResultsAsText()
isAppraiseeClosed($a_user_id)
cleanupMediaobjectUsage()
Cleans up the media objects for all text fields in a test which are using an RTE field.
startSurvey($user_id, $anonymous_id, $appraisee_id)
Starts the survey creating an entry in the database.
$params
Definition: example_049.php:96
setAnonymize($a_anonymize)
set anonymize status
Settings template application class.
& getQuestionblockQuestionIds($questionblock_id)
Returns the question id&#39;s of all questions of a question block.
deleteAllUserData()
Deletes all user data of a survey.
_getAvailableQuestionpools($use_object_id=FALSE, $could_be_offline=FALSE, $showPath=FALSE, $permission="read")
Returns the available question pools for the active user.
isSurveyStarted($user_id, $anonymize_id, $appr_id=0)
Checks if a user already started a survey.
loadQuestionsFromDb()
Loads the survey questions from the database.
deleteAppraisee($a_user_id)
setOutro($outro="")
Sets the outro text.
moveDownQuestionblock($questionblock_id)
Moves a questionblock down in the list of survey questions.
inviteGroup($group_id)
Invites a group to a survey.
getPrecondition($id)
Returns a precondition with a given id.
addQuestionToBlock($question_id, $questionblock_id)