ILIAS  Release_4_2_x_branch Revision 61807
 All Data Structures Namespaces Files Functions Variables Groups Pages
class.ilObjSurvey.php
Go to the documentation of this file.
1 <?php
2 /*
3  +-----------------------------------------------------------------------------+
4  | ILIAS open source |
5  +-----------------------------------------------------------------------------+
6  | Copyright (c) 1998-2006 ILIAS open source, University of Cologne |
7  | |
8  | This program is free software; you can redistribute it and/or |
9  | modify it under the terms of the GNU General Public License |
10  | as published by the Free Software Foundation; either version 2 |
11  | of the License, or (at your option) any later version. |
12  | |
13  | This program is distributed in the hope that it will be useful, |
14  | but WITHOUT ANY WARRANTY; without even the implied warranty of |
15  | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
16  | GNU General Public License for more details. |
17  | |
18  | You should have received a copy of the GNU General Public License |
19  | along with this program; if not, write to the Free Software |
20  | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
21  +-----------------------------------------------------------------------------+
22 */
23 
34 include_once "./classes/class.ilObject.php";
35 include_once "./Modules/Survey/classes/inc.SurveyConstants.php";
36 
37 class ilObjSurvey extends ilObject
38 {
46 
53  var $author;
54 
61 
67  var $outro;
68 
74  var $status;
75 
82 
89 
96 
103 
110 
117 
124 
131 
137 
143 
150 
156 
163  function ilObjSurvey($a_id = 0,$a_call_by_reference = true)
164  {
165  global $ilUser;
166  $this->type = "svy";
167  $this->ilObject($a_id,$a_call_by_reference);
168 
169  $this->survey_id = -1;
170  $this->introduction = "";
171  $this->outro = $this->lng->txt("survey_finished");
172  $this->author = $ilUser->fullname;
173  $this->status = STATUS_OFFLINE;
174  $this->evaluation_access = EVALUATION_ACCESS_OFF;
175  $this->startdate_enabled = 0;
176  $this->enddate_enabled = 0;
177  $this->questions = array();
178  $this->invitation = INVITATION_OFF;
179  $this->invitation_mode = MODE_PREDEFINED_USERS;
180  $this->anonymize = ANONYMIZE_OFF;
181  $this->display_question_titles = QUESTIONTITLES_VISIBLE;
182  $this->surveyCodeSecurity = TRUE;
183  $this->template_id = NULL;
184  $this->pool_usage = true;
185  }
186 
190  function create($a_upload = false)
191  {
192  parent::create();
193  if(!$a_upload)
194  {
195  $this->createMetaData();
196  }
197  }
198 
204  function createMetaData()
205  {
207  $this->saveAuthorToMetadata();
208  }
209 
216  function update()
217  {
218  $this->updateMetaData();
219 
220  if (!parent::update())
221  {
222  return false;
223  }
224 
225  // put here object specific stuff
226 
227  return true;
228  }
229 
230  function createReference()
231  {
233  $this->saveToDb();
234  return $result;
235  }
236 
242  function read($a_force_db = false)
243  {
244  parent::read($a_force_db);
245  $this->loadFromDb();
246  }
247 
254  function addQuestion($question_id)
255  {
256  array_push($this->questions, $question_id);
257  }
258 
259 
266  function delete()
267  {
268  $remove = parent::delete();
269  // always call parent delete function first!!
270  if (!$remove)
271  {
272  return false;
273  }
274 
275  $this->deleteMetaData();
276 
277  // Delete all survey questions, constraints and materials
278  foreach ($this->questions as $question_id)
279  {
280  $this->removeQuestion($question_id);
281  }
282  $this->deleteSurveyRecord();
283 
285  return true;
286  }
287 
294  {
295  global $ilDB;
296 
297  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_svy WHERE survey_id = %s",
298  array('integer'),
299  array($this->getSurveyId())
300  );
301 
302  $result = $ilDB->queryF("SELECT questionblock_fi FROM svy_qblk_qst WHERE survey_fi = %s",
303  array('integer'),
304  array($this->getSurveyId())
305  );
306  $questionblocks = array();
307  while ($row = $ilDB->fetchAssoc($result))
308  {
309  array_push($questionblocks, $row["questionblock_fi"]);
310  }
311  if (count($questionblocks))
312  {
313  $affectedRows = $ilDB->manipulate("DELETE FROM svy_qblk WHERE " . $ilDB->in('questionblock_id', $questionblocks, false, 'integer'));
314  }
315  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE survey_fi = %s",
316  array('integer'),
317  array($this->getSurveyId())
318  );
319  $this->deleteAllUserData();
320 
321  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_anonymous WHERE survey_fi = %s",
322  array('integer'),
323  array($this->getSurveyId())
324  );
325 
326  // delete export files
327  include_once "./Services/Utilities/classes/class.ilUtil.php";
328  $svy_data_dir = ilUtil::getDataDir()."/svy_data";
329  $directory = $svy_data_dir."/svy_".$this->getId();
330  if (is_dir($directory))
331  {
332  include_once "./Services/Utilities/classes/class.ilUtil.php";
333  ilUtil::delDir($directory);
334  }
335 
336  include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php");
337  $mobs = ilObjMediaObject::_getMobsOfObject("svy:html", $this->getId());
338  // remaining usages are not in text anymore -> delete them
339  // and media objects (note: delete method of ilObjMediaObject
340  // checks whether object is used in another context; if yes,
341  // the object is not deleted!)
342  foreach($mobs as $mob)
343  {
344  ilObjMediaObject::_removeUsage($mob, "svy:html", $this->getId());
345  $mob_obj =& new ilObjMediaObject($mob);
346  $mob_obj->delete();
347  }
348  }
349 
355  function deleteAllUserData()
356  {
357  global $ilDB;
358 
359  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
360  array('integer'),
361  array($this->getSurveyId())
362  );
363  $active_array = array();
364  while ($row = $ilDB->fetchAssoc($result))
365  {
366  array_push($active_array, $row["finished_id"]);
367  }
368 
369  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_finished WHERE survey_fi = %s",
370  array('integer'),
371  array($this->getSurveyId())
372  );
373 
374  foreach ($active_array as $active_fi)
375  {
376  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE active_fi = %s",
377  array('integer'),
378  array($active_fi)
379  );
380  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_times WHERE finished_fi = %s",
381  array('integer'),
382  array($active_fi)
383  );
384  }
385  }
386 
392  function removeSelectedSurveyResults($finished_ids)
393  {
394  global $ilDB;
395 
396  foreach ($finished_ids as $finished_id)
397  {
398  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE finished_id = %s",
399  array('integer'),
400  array($finished_id)
401  );
402  $row = $ilDB->fetchAssoc($result);
403 
404  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE active_fi = %s",
405  array('integer'),
406  array($row["finished_id"])
407  );
408 
409  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_finished WHERE finished_id = %s",
410  array('integer'),
411  array($finished_id)
412  );
413 
414  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_times WHERE finished_fi = %s",
415  array('integer'),
416  array($row["finished_id"])
417  );
418  }
419  }
420 
422  {
423  global $ilDB;
424 
425  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s",
426  array('integer'),
427  array($this->getSurveyId())
428  );
429  $participants = array();
430  if ($result->numRows() > 0)
431  {
432  while ($row = $ilDB->fetchAssoc($result))
433  {
434  $userdata = $this->getUserDataFromActiveId($row["finished_id"]);
435  $participants[$userdata["sortname"] . $userdata["active_id"]] = $userdata;
436  }
437  }
438  return $participants;
439  }
440 
454  function notify($a_event,$a_ref_id,$a_parent_non_rbac_id,$a_node_id,$a_params = 0)
455  {
456  global $tree;
457 
458  switch ($a_event)
459  {
460  case "link":
461 
462  //var_dump("<pre>",$a_params,"</pre>");
463  //echo "Module name ".$this->getRefId()." triggered by link event. Objects linked into target object ref_id: ".$a_ref_id;
464  //exit;
465  break;
466 
467  case "cut":
468 
469  //echo "Module name ".$this->getRefId()." triggered by cut event. Objects are removed from target object ref_id: ".$a_ref_id;
470  //exit;
471  break;
472 
473  case "copy":
474 
475  //var_dump("<pre>",$a_params,"</pre>");
476  //echo "Module name ".$this->getRefId()." triggered by copy event. Objects are copied into target object ref_id: ".$a_ref_id;
477  //exit;
478  break;
479 
480  case "paste":
481 
482  //echo "Module name ".$this->getRefId()." triggered by paste (cut) event. Objects are pasted into target object ref_id: ".$a_ref_id;
483  //exit;
484  break;
485 
486  case "new":
487 
488  //echo "Module name ".$this->getRefId()." triggered by paste (new) event. Objects are applied to target object ref_id: ".$a_ref_id;
489  //exit;
490  break;
491  }
492 
493  // At the beginning of the recursive process it avoids second call of the notify function with the same parameter
494  if ($a_node_id==$_GET["ref_id"])
495  {
496  $parent_obj =& $this->ilias->obj_factory->getInstanceByRefId($a_node_id);
497  $parent_type = $parent_obj->getType();
498  if($parent_type == $this->getType())
499  {
500  $a_node_id = (int) $tree->getParentId($a_node_id);
501  }
502  }
503 
504  parent::notify($a_event,$a_ref_id,$a_parent_non_rbac_id,$a_node_id,$a_params);
505  }
506 
513  function isComplete()
514  {
515  if (($this->getTitle()) and (count($this->questions)))
516  {
517  return 1;
518  }
519  else
520  {
521  return 0;
522  }
523  }
524 
531  function _isComplete($obj_id)
532  {
533  $survey = new ilObjSurvey($obj_id, false);
534  $survey->loadFromDb();
535  if (($survey->getTitle()) and (count($survey->questions)))
536  {
537  return 1;
538  }
539  else
540  {
541  return 0;
542  }
543  }
544 
551  function &_getGlobalSurveyData($obj_id)
552  {
553  $survey = new ilObjSurvey($obj_id, false);
554  $survey->loadFromDb();
555  $result = array();
556  if (($survey->getTitle()) and ($survey->author) and (count($survey->questions)))
557  {
558  $result["complete"] = true;
559  }
560  else
561  {
562  $result["complete"] = false;
563  }
564  $result["evaluation_access"] = $survey->getEvaluationAccess();
565  return $result;
566  }
567 
574  {
575  global $ilDB;
576 
577  $complete = 0;
578  if ($this->isComplete())
579  {
580  $complete = 1;
581  }
582  if ($this->getSurveyId() > 0)
583  {
584  $affectedRows = $ilDB->manipulateF("UPDATE svy_svy SET complete = %s, tstamp = %s WHERE survey_id = %s",
585  array('text','integer','integer'),
586  array($this->isComplete(), time(), $this->getSurveyId())
587  );
588  }
589  }
590 
598  function duplicateQuestionForSurvey($question_id, $a_force = false)
599  {
600  global $ilUser;
601 
602  $questiontype = $this->getQuestionType($question_id);
603  $question_gui = $this->getQuestionGUI($questiontype, $question_id);
604 
605  // check if question is a pool question at all, if not do nothing
606  if($this->getId() == $question_gui->object->getObjId() && !$a_force)
607  {
608  return $question_id;
609  }
610 
611  $duplicate_id = $question_gui->object->duplicate(true);
612  return $duplicate_id;
613  }
614 
620  function insertQuestion($question_id)
621  {
622  global $ilDB;
623 
624  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
625  if (!SurveyQuestion::_isComplete($question_id))
626  {
627  return FALSE;
628  }
629  else
630  {
631  // get maximum sequence index in test
632  $result = $ilDB->queryF("SELECT survey_question_id FROM svy_svy_qst WHERE survey_fi = %s",
633  array('integer'),
634  array($this->getSurveyId())
635  );
636  $sequence = $result->numRows();
637  $duplicate_id = $this->duplicateQuestionForSurvey($question_id);
638  $next_id = $ilDB->nextId('svy_svy_qst');
639  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_svy_qst (survey_question_id, survey_fi, question_fi, sequence, tstamp) VALUES (%s, %s, %s, %s, %s)",
640  array('integer', 'integer', 'integer', 'integer', 'integer'),
641  array($next_id, $this->getSurveyId(), $duplicate_id, $sequence, time())
642  );
643  $this->loadQuestionsFromDb();
644  return TRUE;
645  }
646  }
647 
648 
654  function insertQuestionblock($questionblock_id)
655  {
656  global $ilDB;
657  $result = $ilDB->queryF("SELECT svy_qblk.title, svy_qblk.show_questiontext, svy_qblk.show_blocktitle,".
658  " svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst, svy_svy_qst".
659  " WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi".
660  " AND svy_svy_qst.question_fi = svy_qblk_qst.question_fi".
661  " AND svy_qblk.questionblock_id = %s".
662  " ORDER BY svy_svy_qst.sequence",
663  array('integer'),
664  array($questionblock_id)
665  );
666  $questions = array();
667  $show_questiontext = 0;
668  $show_blocktitle = 0;
669  while ($row = $ilDB->fetchAssoc($result))
670  {
671  $duplicate_id = $this->duplicateQuestionForSurvey($row["question_fi"]);
672  array_push($questions, $duplicate_id);
673  $title = $row["title"];
674  $show_questiontext = $row["show_questiontext"];
675  $show_blocktitle = $row["show_blocktitle"];
676  }
677  $this->createQuestionblock($title, $show_questiontext, $show_blocktitle, $questions);
678  }
679 
685  function getAllRTEContent()
686  {
687  $result = array();
688  array_push($result, $this->getIntroduction());
689  array_push($result, $this->getOutro());
690  return $result;
691  }
692 
699  {
700  include_once("./Services/RTE/classes/class.ilRTE.php");
701  $completecontent = "";
702  foreach ($this->getAllRTEContent() as $content)
703  {
704  $completecontent .= $content;
705  }
706  ilRTE::_cleanupMediaObjectUsage($completecontent, $this->getType() . ":html",
707  $this->getId());
708  }
709 
710  public function saveUserSettings($usr_id, $key, $title, $value)
711  {
712  global $ilDB;
713 
714  $next_id = $ilDB->nextId('svy_settings');
715  $affectedRows = $ilDB->insert("svy_settings", array(
716  "settings_id" => array("integer", $next_id),
717  "usr_id" => array("integer", $usr_id),
718  "keyword" => array("text", $key),
719  "title" => array("text", $title),
720  "value" => array("clob", $value)
721  ));
722  }
723 
724  public function deleteUserSettings($id)
725  {
726  global $ilDB;
727 
728  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_settings WHERE settings_id = %s",
729  array('integer'),
730  array($id)
731  );
732  return $affectedRows;
733  }
734 
735  public function getUserSettings($usr_id, $key)
736  {
737  global $ilDB;
738 
739  $result = $ilDB->queryF("SELECT * FROM svy_settings WHERE usr_id = %s AND keyword = %s",
740  array('integer', 'text'),
741  array($usr_id, $key)
742  );
743  $found = array();
744  if ($result->numRows())
745  {
746  while ($row = $ilDB->fetchAssoc($result))
747  {
748  $found[$row['settings_id']] = $row;
749  }
750  }
751  return $found;
752  }
753 
759  function saveToDb()
760  {
761  global $ilDB;
762 
763  include_once("./Services/RTE/classes/class.ilRTE.php");
764  if ($this->getSurveyId() < 1)
765  {
766  $next_id = $ilDB->nextId('svy_svy');
767  $affectedRows = $ilDB->insert("svy_svy", array(
768  "survey_id" => array("integer", $next_id),
769  "obj_fi" => array("integer", $this->getId()),
770  "author" => array("text", $this->getAuthor()),
771  "introduction" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getIntroduction(), 0)),
772  "outro" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getOutro(), 0)),
773  "status" => array("text", $this->getStatus()),
774  "startdate" => array("text", $this->getStartDate()),
775  "enddate" => array("text", $this->getEndDate()),
776  "evaluation_access" => array("text", $this->getEvaluationAccess()),
777  "invitation" => array("text", $this->getInvitation()),
778  "invitation_mode" => array("text", $this->getInvitationMode()),
779  "complete" => array("text", $this->isComplete()),
780  "created" => array("integer", time()),
781  "anonymize" => array("text", $this->getAnonymize()),
782  "show_question_titles" => array("text", $this->getShowQuestionTitles()),
783  "mailnotification" => array('integer', ($this->getMailNotification()) ? 1 : 0),
784  "mailaddresses" => array('text', strlen($this->getMailAddresses()) ? $this->getMailAddresses() : NULL),
785  "mailparticipantdata" => array('text', strlen($this->getMailParticipantData()) ? $this->getMailParticipantData() : NULL),
786  "tstamp" => array("integer", time()),
787  "template_id" => array("integer", $this->getTemplate()),
788  "pool_usage" => array("integer", $this->getPoolUsage())
789  ));
790  $this->setSurveyId($next_id);
791  }
792  else
793  {
794  $affectedRows = $ilDB->update("svy_svy", array(
795  "author" => array("text", $this->getAuthor()),
796  "introduction" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getIntroduction(), 0)),
797  "outro" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getOutro(), 0)),
798  "status" => array("text", $this->getStatus()),
799  "startdate" => array("text", $this->getStartDate()),
800  "enddate" => array("text", $this->getEndDate()),
801  "evaluation_access" => array("text", $this->getEvaluationAccess()),
802  "invitation" => array("text", $this->getInvitation()),
803  "invitation_mode" => array("text", $this->getInvitationMode()),
804  "complete" => array("text", $this->isComplete()),
805  "anonymize" => array("text", $this->getAnonymize()),
806  "show_question_titles" => array("text", $this->getShowQuestionTitles()),
807  "mailnotification" => array('integer', ($this->getMailNotification()) ? 1 : 0),
808  "mailaddresses" => array('text', strlen($this->getMailAddresses()) ? $this->getMailAddresses() : NULL),
809  "mailparticipantdata" => array('text', strlen($this->getMailParticipantData()) ? $this->getMailParticipantData() : NULL),
810  "tstamp" => array("integer", time()),
811  "template_id" => array("integer", $this->getTemplate()),
812  "pool_usage" => array("integer", $this->getPoolUsage())
813  ), array(
814  "survey_id" => array("integer", $this->getSurveyId())
815  ));
816  }
817  if ($affectedRows)
818  {
819  // save questions to db
820  $this->saveQuestionsToDb();
821  }
822  }
823 
830  function saveQuestionsToDb()
831  {
832  global $ilDB;
833  // save old questions state
834  $old_questions = array();
835  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE survey_fi = %s",
836  array('integer'),
837  array($this->getSurveyId())
838  );
839  if ($result->numRows())
840  {
841  while ($row = $ilDB->fetchAssoc($result))
842  {
843  $old_questions[$row["question_fi"]] = $row;
844  }
845  }
846 
847  // delete existing question relations
848  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_svy_qst WHERE survey_fi = %s",
849  array('integer'),
850  array($this->getSurveyId())
851  );
852  // create new question relations
853  foreach ($this->questions as $key => $value)
854  {
855  $next_id = $ilDB->nextId('svy_svy_qst');
856  $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)",
857  array('integer','integer','integer','text','integer','integer'),
858  array($next_id, $this->getSurveyId(), $value, (strlen($old_questions[$value]["heading"])) ? $old_questions[$value]["heading"] : NULL, $key, time())
859  );
860  }
861  }
862 
870  function getAnonymousId($id)
871  {
872  global $ilDB;
873  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_finished WHERE anonymous_id = %s",
874  array('text'),
875  array($id)
876  );
877  if ($result->numRows())
878  {
879  $row = $ilDB->fetchAssoc($result);
880  return $row["anonymous_id"];
881  }
882  else
883  {
884  return "";
885  }
886  }
887 
894  function getQuestionGUI($questiontype, $question_id)
895  {
896  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php";
897  return SurveyQuestionGUI::_getQuestionGUI($questiontype, $question_id);
898  }
899 
907  function getQuestionType($question_id)
908  {
909  global $ilDB;
910  if ($question_id < 1) return -1;
911  $result = $ilDB->queryF("SELECT type_tag FROM svy_question, svy_qtype WHERE svy_question.question_id = %s AND " .
912  "svy_question.questiontype_fi = svy_qtype.questiontype_id",
913  array('integer'),
914  array($question_id)
915  );
916  if ($result->numRows() == 1)
917  {
918  $data = $ilDB->fetchAssoc($result);
919  return $data["type_tag"];
920  }
921  else
922  {
923  return "";
924  }
925  }
926 
933  function getSurveyId()
934  {
935  return $this->survey_id;
936  }
937 
941  function setAnonymize($a_anonymize)
942  {
943  switch ($a_anonymize)
944  {
945  case ANONYMIZE_OFF:
946  case ANONYMIZE_ON:
948  case ANONYMIZE_CODE_ALL:
949  $this->anonymize = $a_anonymize;
950  break;
951  default:
952  $this->anonymize = ANONYMIZE_OFF;
953  break;
954  }
955  }
956 
962  function getAnonymize()
963  {
964  return ($this->anonymize) ? $this->anonymize : 0;
965  }
966 
968  {
969  if ($this->getAnonymize() == ANONYMIZE_CODE_ALL)
970  {
971  return true;
972  }
973  else
974  {
975  return false;
976  }
977  }
978 
985  {
986  if ($this->getAnonymize() == ANONYMIZE_FREEACCESS)
987  {
988  return true;
989  }
990  else
991  {
992  return false;
993  }
994  }
995 
1001  function loadFromDb()
1002  {
1003  global $ilDB;
1004  $result = $ilDB->queryF("SELECT * FROM svy_svy WHERE obj_fi = %s",
1005  array('integer'),
1006  array($this->getId())
1007  );
1008  if ($result->numRows() == 1)
1009  {
1010  $data = $ilDB->fetchAssoc($result);
1011  $this->setSurveyId($data["survey_id"]);
1012  $this->setAuthor($data["author"]);
1013  include_once("./Services/RTE/classes/class.ilRTE.php");
1014  $this->setIntroduction(ilRTE::_replaceMediaObjectImageSrc($data["introduction"], 1));
1015  if (strcmp($data["outro"], "survey_finished") == 0)
1016  {
1017  $this->setOutro($this->lng->txt("survey_finished"));
1018  }
1019  else
1020  {
1021  $this->setOutro(ilRTE::_replaceMediaObjectImageSrc($data["outro"], 1));
1022  }
1023  $this->setInvitation($data["invitation"]);
1024  $this->setInvitationMode($data["invitation_mode"]);
1025  $this->setShowQuestionTitles($data["show_question_titles"]);
1026  $this->setStartDate($data["startdate"]);
1027  $this->setStartDateEnabled(strlen($data["startdate"]));
1028  $this->setEndDate($data["enddate"]);
1029  $this->setEndDateEnabled(strlen($data["enddate"]));
1030  $this->setAnonymize($data["anonymize"]);
1031  $this->setEvaluationAccess($data["evaluation_access"]);
1032  $this->loadQuestionsFromDb();
1033  $this->setStatus($data["status"]);
1034  $this->setMailNotification($data['mailnotification']);
1035  $this->setMailAddresses($data['mailaddresses']);
1036  $this->setMailParticipantData($data['mailparticipantdata']);
1037  $this->setTemplate($data['template_id']);
1038  $this->setPoolUsage($data['pool_usage']);
1039  }
1040  }
1041 
1049  {
1050  global $ilDB;
1051  $this->questions = array();
1052  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE survey_fi = %s ORDER BY sequence",
1053  array('integer'),
1054  array($this->getSurveyId())
1055  );
1056  while ($data = $ilDB->fetchAssoc($result))
1057  {
1058  $this->questions[$data["sequence"]] = $data["question_fi"];
1059  }
1060  }
1061 
1069  function setStartDateEnabled($enabled = false)
1070  {
1071  $this->startdate_enabled = ($enabled) ? $enabled : 0;
1072  }
1073 
1082  {
1083  return ($this->startdate_enabled) ? $this->startdate_enabled : 0;
1084  }
1085 
1093  function setEndDateEnabled($enabled = false)
1094  {
1095  $this->enddate_enabled = ($enabled) ? $enabled : 0;
1096  }
1097 
1106  {
1107  return ($this->enddate_enabled) ? $this->enddate_enabled : 0;
1108  }
1109 
1117  function setAuthor($author = "")
1118  {
1119  $this->author = $author;
1120  }
1121 
1131  function saveAuthorToMetadata($a_author = "")
1132  {
1133  $md =& new ilMD($this->getId(), 0, $this->getType());
1134  $md_life =& $md->getLifecycle();
1135  if (!$md_life)
1136  {
1137  if (strlen($a_author) == 0)
1138  {
1139  global $ilUser;
1140  $a_author = $ilUser->getFullname();
1141  }
1142 
1143  $md_life =& $md->addLifecycle();
1144  $md_life->save();
1145  $con =& $md_life->addContribute();
1146  $con->setRole("Author");
1147  $con->save();
1148  $ent =& $con->addEntity();
1149  $ent->setEntity($a_author);
1150  $ent->save();
1151  }
1152  }
1153 
1161  function getAuthor()
1162  {
1163  $author = array();
1164  include_once "./Services/MetaData/classes/class.ilMD.php";
1165  $md =& new ilMD($this->getId(), 0, $this->getType());
1166  $md_life =& $md->getLifecycle();
1167  if ($md_life)
1168  {
1169  $ids =& $md_life->getContributeIds();
1170  foreach ($ids as $id)
1171  {
1172  $md_cont =& $md_life->getContribute($id);
1173  if (strcmp($md_cont->getRole(), "Author") == 0)
1174  {
1175  $entids =& $md_cont->getEntityIds();
1176  foreach ($entids as $entid)
1177  {
1178  $md_ent =& $md_cont->getEntity($entid);
1179  array_push($author, $md_ent->getEntity());
1180  }
1181  }
1182  }
1183  }
1184  return join($author, ",");
1185  }
1186 
1193  public function getShowQuestionTitles()
1194  {
1195  return ($this->display_question_titles) ? 1 : 0;
1196  }
1197 
1204  public function setShowQuestionTitles($a_show)
1205  {
1206  $this->display_question_titles = ($a_show) ? 1 : 0;
1207  }
1208 
1216  {
1217  $this->display_question_titles = 1;
1218  }
1219 
1227  {
1228  $this->display_question_titles = 0;
1229  }
1230 
1239  {
1240  global $ilDB;
1241  global $ilAccess;
1242  $this->invitation = $invitation;
1243  if ($invitation == INVITATION_OFF)
1244  {
1245  $this->disinviteAllUsers();
1246  }
1247  else if ($invitation == INVITATION_ON)
1248  {
1249  if ($this->getInvitationMode() == MODE_UNLIMITED)
1250  {
1251  $result = $ilDB->query("SELECT usr_id FROM usr_data");
1252  while ($row = $ilDB->fetchAssoc($result))
1253  {
1254  if ($ilAccess->checkAccessOfUser($row["usr_id"], "read", "", $this->getRefId(), "svy", $this->getId()))
1255  {
1256  $this->inviteUser($row['usr_id']);
1257  }
1258  }
1259  }
1260  }
1261  }
1262 
1271  {
1272  $this->invitation_mode = $invitation_mode;
1273  }
1274 
1284  {
1285  $this->invitation_mode = $invitation_mode;
1286  $this->setInvitation($invitation);
1287  }
1288 
1295  public function setIntroduction($introduction = "")
1296  {
1297  $this->introduction = $introduction;
1298  }
1299 
1306  public function setOutro($outro = "")
1307  {
1308  $this->outro = $outro;
1309  }
1310 
1318  function getInvitation()
1319  {
1320  return ($this->invitation) ? $this->invitation : INVITATION_OFF;
1321  }
1322 
1330  function getInvitationMode()
1331  {
1332  include_once "./Services/Administration/classes/class.ilSetting.php";
1333  $surveySetting = new ilSetting("survey");
1334  $unlimited_invitation = $surveySetting->get("unlimited_invitation");
1335  if (!$unlimited_invitation && $this->invitation_mode == MODE_UNLIMITED)
1336  {
1337  return MODE_PREDEFINED_USERS;
1338  }
1339  else
1340  {
1341  return ($this->invitation_mode) ? $this->invitation_mode : MODE_UNLIMITED;
1342  }
1343  }
1344 
1352  function getStatus()
1353  {
1354  return ($this->status) ? $this->status : STATUS_OFFLINE;
1355  }
1356 
1364  function isOnline()
1365  {
1366  return ($this->status == STATUS_ONLINE) ? true : false;
1367  }
1368 
1376  function isOffline()
1377  {
1378  return ($this->status == STATUS_OFFLINE) ? true : false;
1379  }
1380 
1390  {
1391  $result = "";
1392  if (($status == STATUS_ONLINE) && (count($this->questions) == 0))
1393  {
1394  $this->status = STATUS_OFFLINE;
1395  $result = $this->lng->txt("cannot_switch_to_online_no_questions");
1396  }
1397  else
1398  {
1399  $this->status = $status;
1400  }
1401  return $result;
1402  }
1403 
1411  function getStartDate()
1412  {
1413  return (strlen($this->start_date)) ? $this->start_date : NULL;
1414  }
1415 
1422  function canStartSurvey($anonymous_id = NULL)
1423  {
1424  global $ilAccess;
1425 
1426  $result = TRUE;
1427  $messages = array();
1428  $edit_settings = false;
1429  // check start date
1430  if ($this->getStartDateEnabled())
1431  {
1432  if (preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getStartDate(), $matches))
1433  {
1434  $epoch_time = mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1435  $now = mktime();
1436  if ($now < $epoch_time)
1437  {
1438  array_push($messages,$this->lng->txt('start_date_not_reached').' ('.
1440  $result = FALSE;
1441  $edit_settings = true;
1442  }
1443  }
1444  }
1445  // check end date
1446  if ($this->getEndDateEnabled())
1447  {
1448  if (preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getEndDate(), $matches))
1449  {
1450  $epoch_time = mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1451  $now = mktime();
1452  if ($now > $epoch_time)
1453  {
1454  array_push($messages,$this->lng->txt('end_date_reached').' ('.
1456  $result = FALSE;
1457  $edit_settings = true;
1458  }
1459  }
1460  }
1461  // check online status
1462  if ($this->getStatus() == STATUS_OFFLINE)
1463  {
1464  array_push($messages, $this->lng->txt("survey_is_offline"));
1465  $result = FALSE;
1466  $edit_settings = true;
1467  }
1468  // check rbac permissions
1469  if (!$ilAccess->checkAccess("read", "", $this->ref_id))
1470  {
1471  array_push($messages, $this->lng->txt("cannot_participate_survey"));
1472  $result = FALSE;
1473  }
1474  // 2. check previous access
1475  if (!$result["error"])
1476  {
1477  global $ilUser;
1478  $survey_started = $this->isSurveyStarted($ilUser->getId(), $anonymous_id);
1479  if ($survey_started === 1)
1480  {
1481  array_push($messages, $this->lng->txt("already_completed_survey"));
1482  $result = FALSE;
1483  }
1484  }
1485  return array(
1486  "result" => $result,
1487  "messages" => $messages,
1488  "edit_settings" => $edit_settings
1489  );
1490  }
1491 
1499  function setStartDate($start_date = "")
1500  {
1501  $this->start_date = $start_date;
1502  }
1503 
1512  function setStartDateAndTime($start_date = "", $start_time)
1513  {
1514  $y = ''; $m = ''; $d = ''; $h = ''; $i = ''; $s = '';
1515  if (preg_match("/(\d{4})-(\d{2})-(\d{2})/", $start_date, $matches))
1516  {
1517  $y = $matches[1];
1518  $m = $matches[2];
1519  $d = $matches[3];
1520  }
1521  if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $start_time, $matches))
1522  {
1523  $h = $matches[1];
1524  $i = $matches[2];
1525  $s = $matches[3];
1526  }
1527  $this->start_date = sprintf('%04d%02d%02d%02d%02d%02d', $y, $m, $d, $h, $i, $s);
1528  }
1529 
1537  function getStartMonth()
1538  {
1539  $dt = new ilDateTime($this->getStartDate(), IL_CAL_TIMESTAMP);
1540  return $dt->get(IL_CAL_FKT_DATE, 'm');
1541  }
1542 
1550  function getStartDay()
1551  {
1552  $dt = new ilDateTime($this->getStartDate(), IL_CAL_TIMESTAMP);
1553  return $dt->get(IL_CAL_FKT_DATE, 'd');
1554  }
1555 
1563  function getStartYear()
1564  {
1565  $dt = new ilDateTime($this->getStartDate(), IL_CAL_TIMESTAMP);
1566  return $dt->get(IL_CAL_FKT_DATE, 'Y');
1567  }
1568 
1576  function getStartHour()
1577  {
1578  $dt = new ilDateTime($this->getStartDate(), IL_CAL_TIMESTAMP);
1579  return $dt->get(IL_CAL_FKT_DATE, 'H');
1580  }
1581 
1589  function getStartMinute()
1590  {
1591  $dt = new ilDateTime($this->getStartDate(), IL_CAL_TIMESTAMP);
1592  return $dt->get(IL_CAL_FKT_DATE, 'i');
1593  }
1594 
1602  function getEndDate()
1603  {
1604  return (strlen($this->end_date)) ? $this->end_date : NULL;
1605  }
1606 
1614  function setEndDate($end_date = "")
1615  {
1616  $this->end_date = $end_date;
1617  }
1618 
1627  function setEndDateAndTime($end_date = "", $end_time)
1628  {
1629  $y = ''; $m = ''; $d = ''; $h = ''; $i = ''; $s = '';
1630  if (preg_match("/(\d{4})-(\d{2})-(\d{2})/", $end_date, $matches))
1631  {
1632  $y = $matches[1];
1633  $m = $matches[2];
1634  $d = $matches[3];
1635  }
1636  if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $end_time, $matches))
1637  {
1638  $h = $matches[1];
1639  $i = $matches[2];
1640  $s = $matches[3];
1641  }
1642  $this->end_date = sprintf('%04d%02d%02d%02d%02d%02d', $y, $m, $d, $h, $i, $s);
1643  }
1644 
1652  function getEndMonth()
1653  {
1654  $dt = new ilDateTime($this->getEndDate(), IL_CAL_TIMESTAMP);
1655  return $dt->get(IL_CAL_FKT_DATE, 'm');
1656  }
1657 
1665  function getEndDay()
1666  {
1667  $dt = new ilDateTime($this->getEndDate(), IL_CAL_TIMESTAMP);
1668  return $dt->get(IL_CAL_FKT_DATE, 'd');
1669  }
1670 
1678  function getEndYear()
1679  {
1680  $dt = new ilDateTime($this->getEndDate(), IL_CAL_TIMESTAMP);
1681  return $dt->get(IL_CAL_FKT_DATE, 'Y');
1682  }
1683 
1691  function getEndHour()
1692  {
1693  $dt = new ilDateTime($this->getEndDate(), IL_CAL_TIMESTAMP);
1694  return $dt->get(IL_CAL_FKT_DATE, 'H');
1695  }
1696 
1704  function getEndMinute()
1705  {
1706  $dt = new ilDateTime($this->getEndDate(), IL_CAL_TIMESTAMP);
1707  return $dt->get(IL_CAL_FKT_DATE, 'i');
1708  }
1709 
1718  {
1719  return ($this->evaluation_access) ? $this->evaluation_access : EVALUATION_ACCESS_OFF;
1720  }
1721 
1730  {
1731  $this->evaluation_access = ($evaluation_access) ? $evaluation_access : EVALUATION_ACCESS_OFF;
1732  }
1733 
1741  function getIntroduction()
1742  {
1743  return (strlen($this->introduction)) ? $this->introduction : NULL;
1744  }
1745 
1753  function getOutro()
1754  {
1755  return (strlen($this->outro)) ? $this->outro : NULL;
1756  }
1757 
1765  {
1766  global $ilDB;
1767  $existing_questions = array();
1768  $result = $ilDB->queryF("SELECT svy_question.original_id FROM svy_question, svy_svy_qst WHERE " .
1769  "svy_svy_qst.survey_fi = %s AND svy_svy_qst.question_fi = svy_question.question_id",
1770  array('integer'),
1771  array($this->getSurveyId())
1772  );
1773  while ($data = $ilDB->fetchAssoc($result))
1774  {
1775  if($data["original_id"])
1776  {
1777  array_push($existing_questions, $data["original_id"]);
1778  }
1779  }
1780  return $existing_questions;
1781  }
1782 
1789  function &getQuestionpoolTitles($could_be_offline = FALSE, $showPath = FALSE)
1790  {
1791  include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php";
1792  return ilObjSurveyQuestionPool::_getAvailableQuestionpools($use_object_id = TRUE, $could_be_offline, $showPath);
1793  }
1794 
1801  function moveUpQuestion($question_id)
1802  {
1803  $move_questions = array($question_id);
1804  $pages =& $this->getSurveyPages();
1805  $pageindex = -1;
1806  foreach ($pages as $idx => $page)
1807  {
1808  if ($page[0]["question_id"] == $question_id)
1809  {
1810  $pageindex = $idx;
1811  }
1812  }
1813  if ($pageindex > 0)
1814  {
1815  $this->moveQuestions($move_questions, $pages[$pageindex-1][0]["question_id"], 0);
1816  }
1817  else
1818  {
1819  // move up a question in a questionblock
1820  $questions = $this->getSurveyQuestions();
1821  $questions = array_keys($questions);
1822  $index = array_search($question_id, $questions);
1823  if (($index !== FALSE) && ($index > 0))
1824  {
1825  $this->moveQuestions($move_questions, $questions[$index-1], 0);
1826  }
1827  }
1828  }
1829 
1835  public function moveDownQuestion($question_id)
1836  {
1837  $move_questions = array($question_id);
1838  $pages =& $this->getSurveyPages();
1839  $pageindex = -1;
1840  foreach ($pages as $idx => $page)
1841  {
1842  if (($page[0]["question_id"] == $question_id) && (strcmp($page[0]["questionblock_id"], "") == 0))
1843  {
1844  $pageindex = $idx;
1845  }
1846  }
1847  if (($pageindex < count($pages)-1) && ($pageindex >= 0))
1848  {
1849  $this->moveQuestions($move_questions, $pages[$pageindex+1][count($pages[$pageindex+1])-1]["question_id"], 1);
1850  }
1851  else
1852  {
1853  // move down a question in a questionblock
1854  $questions = $this->getSurveyQuestions();
1855  $questions = array_keys($questions);
1856  $index = array_search($question_id, $questions);
1857  if (($index !== FALSE) && ($index < count($questions)-1))
1858  {
1859  $this->moveQuestions($move_questions, $questions[$index+1], 1);
1860  }
1861  }
1862  }
1863 
1870  function moveUpQuestionblock($questionblock_id)
1871  {
1872  $pages =& $this->getSurveyPages();
1873  $move_questions = array();
1874  $pageindex = -1;
1875  foreach ($pages as $idx => $page)
1876  {
1877  if ($page[0]["questionblock_id"] == $questionblock_id)
1878  {
1879  foreach ($page as $pageidx => $question)
1880  {
1881  array_push($move_questions, $question["question_id"]);
1882  }
1883  $pageindex = $idx;
1884  }
1885  }
1886  if ($pageindex > 0)
1887  {
1888  $this->moveQuestions($move_questions, $pages[$pageindex-1][0]["question_id"], 0);
1889  }
1890  }
1891 
1898  function moveDownQuestionblock($questionblock_id)
1899  {
1900  $pages =& $this->getSurveyPages();
1901  $move_questions = array();
1902  $pageindex = -1;
1903  foreach ($pages as $idx => $page)
1904  {
1905  if ($page[0]["questionblock_id"] == $questionblock_id)
1906  {
1907  foreach ($page as $pageidx => $question)
1908  {
1909  array_push($move_questions, $question["question_id"]);
1910  }
1911  $pageindex = $idx;
1912  }
1913  }
1914  if ($pageindex < count($pages)-1)
1915  {
1916  $this->moveQuestions($move_questions, $pages[$pageindex+1][count($pages[$pageindex+1])-1]["question_id"], 1);
1917  }
1918  }
1919 
1928  function moveQuestions($move_questions, $target_index, $insert_mode)
1929  {
1930  $array_pos = array_search($target_index, $this->questions);
1931  if ($insert_mode == 0)
1932  {
1933  $part1 = array_slice($this->questions, 0, $array_pos);
1934  $part2 = array_slice($this->questions, $array_pos);
1935  }
1936  else if ($insert_mode == 1)
1937  {
1938  $part1 = array_slice($this->questions, 0, $array_pos + 1);
1939  $part2 = array_slice($this->questions, $array_pos + 1);
1940  }
1941  foreach ($move_questions as $question_id)
1942  {
1943  if (!(array_search($question_id, $part1) === FALSE))
1944  {
1945  unset($part1[array_search($question_id, $part1)]);
1946  }
1947  if (!(array_search($question_id, $part2) === FALSE))
1948  {
1949  unset($part2[array_search($question_id, $part2)]);
1950  }
1951  }
1952  $part1 = array_values($part1);
1953  $part2 = array_values($part2);
1954  $this->questions = array_values(array_merge($part1, $move_questions, $part2));
1955  foreach ($move_questions as $question_id)
1956  {
1957  $constraints = $this->getConstraints($question_id);
1958  foreach ($constraints as $idx => $constraint)
1959  {
1960  foreach ($part2 as $next_question_id)
1961  {
1962  if ($constraint["question"] == $next_question_id)
1963  {
1964  // constraint concerning a question that follows -> delete constraint
1965  $this->deleteConstraint($constraint["id"]);
1966  }
1967  }
1968  }
1969  }
1970  $this->saveQuestionsToDb();
1971  }
1972 
1979  function removeQuestion($question_id)
1980  {
1981  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
1982  $question =& $this->_instanciateQuestion($question_id);
1983  $question->delete($question_id);
1984  $this->removeConstraintsConcerningQuestion($question_id);
1985  }
1986 
1994  {
1995  global $ilDB;
1996  $result = $ilDB->queryF("SELECT constraint_fi FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s",
1997  array('integer','integer'),
1998  array($question_id, $this->getSurveyId())
1999  );
2000  if ($result->numRows() > 0)
2001  {
2002  $remove_constraints = array();
2003  while ($row = $ilDB->fetchAssoc($result))
2004  {
2005  array_push($remove_constraints, $row["constraint_fi"]);
2006  }
2007  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s",
2008  array('integer','integer'),
2009  array($question_id, $this->getSurveyId())
2010  );
2011  foreach ($remove_constraints as $key => $constraint_id)
2012  {
2013  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_constraint WHERE constraint_id = %s",
2014  array('integer'),
2015  array($constraint_id)
2016  );
2017  }
2018  }
2019  }
2020 
2028  function removeQuestions($remove_questions, $remove_questionblocks)
2029  {
2030  global $ilDB;
2031 
2032  $block_sizes = array();
2033  foreach ($this->getSurveyQuestions() as $question_id => $data)
2034  {
2035  if (in_array($question_id, $remove_questions) or in_array($data["questionblock_id"], $remove_questionblocks))
2036  {
2037  unset($this->questions[array_search($question_id, $this->questions)]);
2038  $this->removeQuestion($question_id);
2039  }
2040  else if($data["questionblock_id"])
2041  {
2042  $block_sizes[$data["questionblock_id"]]++;
2043  }
2044  }
2045 
2046  // blocks with just 1 question need to be deleted
2047  foreach($block_sizes as $block_id => $size)
2048  {
2049  if($size < 2)
2050  {
2051  $remove_questionblocks[] = $block_id;
2052  }
2053  }
2054 
2055  foreach (array_unique($remove_questionblocks) as $questionblock_id)
2056  {
2057  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk WHERE questionblock_id = %s",
2058  array('integer'),
2059  array($questionblock_id)
2060  );
2061  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s",
2062  array('integer','integer'),
2063  array($questionblock_id, $this->getSurveyId())
2064  );
2065  }
2066 
2067  $this->questions = array_values($this->questions);
2068  $this->saveQuestionsToDb();
2069  }
2070 
2077  function unfoldQuestionblocks($questionblocks)
2078  {
2079  global $ilDB;
2080  foreach ($questionblocks as $index)
2081  {
2082  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk WHERE questionblock_id = %s",
2083  array('integer'),
2084  array($index)
2085  );
2086  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s",
2087  array('integer','integer'),
2088  array($index, $this->getSurveyId())
2089  );
2090  }
2091  }
2092 
2093  function removeQuestionFromBlock($question_id, $questionblock_id)
2094  {
2095  global $ilDB;
2096 
2097  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s AND question_fi = %s",
2098  array('integer','integer','integer'),
2099  array($questionblock_id, $this->getSurveyId(), $question_id)
2100  );
2101  }
2102 
2103  function addQuestionToBlock($question_id, $questionblock_id)
2104  {
2105  global $ilDB;
2106 
2107 
2108  $next_id = $ilDB->nextId('svy_qblk_qst');
2109  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, " .
2110  "question_fi) VALUES (%s, %s, %s, %s)",
2111  array('integer','integer','integer','integer'),
2112  array($next_id, $this->getSurveyId(), $questionblock_id, $question_id)
2113  );
2114  }
2115 
2122  function &getQuestionblockQuestions($questionblock_id)
2123  {
2124  global $ilDB;
2125  $titles = array();
2126  $result = $ilDB->queryF("SELECT svy_question.title, svy_qblk_qst.question_fi, svy_qblk_qst.survey_fi FROM ".
2127  "svy_qblk, svy_qblk_qst, svy_question WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND " .
2128  "svy_question.question_id = svy_qblk_qst.question_fi AND svy_qblk.questionblock_id = %s",
2129  array('integer'),
2130  array($questionblock_id)
2131  );
2132  $survey_id = "";
2133  while ($row = $ilDB->fetchAssoc($result))
2134  {
2135  $titles[$row["question_fi"]] = $row["title"];
2136  $survey_id = $row["survey_fi"];
2137  }
2138  $result = $ilDB->queryF("SELECT question_fi, sequence FROM svy_svy_qst WHERE survey_fi = %s ORDER BY sequence",
2139  array('integer'),
2140  array($survey_id)
2141  );
2142  $resultarray = array();
2143  $counter = 1;
2144  while ($row = $ilDB->fetchAssoc($result))
2145  {
2146  if (array_key_exists($row["question_fi"], $titles))
2147  {
2148  $resultarray[$counter++] = $titles[$row["question_fi"]];
2149  }
2150  }
2151  return $resultarray;
2152  }
2153 
2160  function &getQuestionblockQuestionIds($questionblock_id)
2161  {
2162  global $ilDB;
2163  $result = $ilDB->queryF("SELECT question_fi FROM svy_qblk_qst WHERE questionblock_fi = %s",
2164  array("integer"),
2165  array($questionblock_id)
2166  );
2167  $ids = array();
2168  if ($result->numRows())
2169  {
2170  while ($data = $ilDB->fetchAssoc($result))
2171  {
2172  array_push($ids, $data['question_fi']);
2173  }
2174  }
2175  return $ids;
2176  }
2177 
2185  function getQuestionblock($questionblock_id)
2186  {
2187  global $ilDB;
2188  $result = $ilDB->queryF("SELECT * FROM svy_qblk WHERE questionblock_id = %s",
2189  array('integer'),
2190  array($questionblock_id)
2191  );
2192  return $ilDB->fetchAssoc($result);
2193  }
2194 
2202  function _getQuestionblock($questionblock_id)
2203  {
2204  global $ilDB;
2205  $result = $ilDB->queryF("SELECT * FROM svy_qblk WHERE questionblock_id = %s",
2206  array('integer'),
2207  array($questionblock_id)
2208  );
2209  $row = $ilDB->fetchAssoc($result);
2210  return $row;
2211  }
2212 
2221  function _addQuestionblock($title = "", $owner = 0)
2222  {
2223  global $ilDB;
2224  $next_id = $ilDB->nextId('svy_qblk');
2225  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk (questionblock_id, title, owner_fi, tstamp) " .
2226  "VALUES (%s, %s, %s, %s)",
2227  array('integer','text','integer','integer'),
2228  array($next_id, $title, $owner, time())
2229  );
2230  return $next_id;
2231  }
2232 
2240  function createQuestionblock($title, $show_questiontext, $show_blocktitle, $questions)
2241  {
2242  global $ilDB;
2243 
2244  // if the selected questions are not in a continous selection, move all questions of the
2245  // questionblock at the position of the first selected question
2246  $this->moveQuestions($questions, $questions[0], 0);
2247 
2248  // now save the question block
2249  global $ilUser;
2250  $next_id = $ilDB->nextId('svy_qblk');
2251  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk (questionblock_id, title, show_questiontext,".
2252  " show_blocktitle, owner_fi, tstamp) VALUES (%s, %s, %s, %s, %s, %s)",
2253  array('integer','text','text','text','integer','integer'),
2254  array($next_id, $title, $show_questiontext, $show_blocktitle, $ilUser->getId(), time())
2255  );
2256  if ($affectedRows)
2257  {
2258  $questionblock_id = $next_id;
2259  foreach ($questions as $index)
2260  {
2261  $next_id = $ilDB->nextId('svy_qblk_qst');
2262  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, " .
2263  "question_fi) VALUES (%s, %s, %s, %s)",
2264  array('integer','integer','integer','integer'),
2265  array($next_id, $this->getSurveyId(), $questionblock_id, $index)
2266  );
2267  $this->deleteConstraints($index);
2268  }
2269  }
2270  }
2271 
2279  function modifyQuestionblock($questionblock_id, $title, $show_questiontext, $show_blocktitle)
2280  {
2281  global $ilDB;
2282  $affectedRows = $ilDB->manipulateF("UPDATE svy_qblk SET title = %s, show_questiontext = %s,".
2283  " show_blocktitle = %s WHERE questionblock_id = %s",
2284  array('text','text','text','integer'),
2285  array($title, $show_questiontext, $show_blocktitle, $questionblock_id)
2286  );
2287  }
2288 
2295  function deleteConstraints($question_id)
2296  {
2297  global $ilDB;
2298  $result = $ilDB->queryF("SELECT constraint_fi FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s",
2299  array('integer','integer'),
2300  array($question_id, $this->getSurveyId())
2301  );
2302  $constraints = array();
2303  while ($row = $ilDB->fetchAssoc($result))
2304  {
2305  array_push($constraints, $row["constraint_fi"]);
2306  }
2307  foreach ($constraints as $constraint_id)
2308  {
2309  $this->deleteConstraint($constraint_id);
2310  }
2311  }
2312 
2320  function deleteConstraint($constraint_id)
2321  {
2322  global $ilDB;
2323  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_constraint WHERE constraint_id = %s",
2324  array('integer'),
2325  array($constraint_id)
2326  );
2327  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_constraint WHERE constraint_fi = %s",
2328  array('integer'),
2329  array($constraint_id)
2330  );
2331  }
2332 
2338  public function &getSurveyQuestions($with_answers = false)
2339  {
2340  global $ilDB;
2341  $obligatory_states =& $this->getObligatoryStates();
2342  // get questionblocks
2343  $all_questions = array();
2344  $result = $ilDB->queryF("SELECT svy_qtype.type_tag, svy_qtype.plugin, svy_question.question_id, ".
2345  "svy_svy_qst.heading FROM svy_qtype, svy_question, svy_svy_qst WHERE svy_svy_qst.survey_fi = %s AND " .
2346  "svy_svy_qst.question_fi = svy_question.question_id AND svy_question.questiontype_fi = svy_qtype.questiontype_id " .
2347  "ORDER BY svy_svy_qst.sequence",
2348  array('integer'),
2349  array($this->getSurveyId())
2350  );
2351  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
2352  while ($row = $ilDB->fetchAssoc($result))
2353  {
2354  $add = true;
2355  if ($row["plugin"])
2356  {
2357  if (!$this->isPluginActive($row["type_tag"]))
2358  {
2359  $add = false;
2360  }
2361  }
2362  if ($add)
2363  {
2364  $question =& $this->_instanciateQuestion($row["question_id"]);
2365  $questionrow = $question->_getQuestionDataArray($row["question_id"]);
2366  foreach ($row as $key => $value)
2367  {
2368  $questionrow[$key] = $value;
2369  }
2370  $all_questions[$row["question_id"]] = $questionrow;
2371  $all_questions[$row["question_id"]]["usableForPrecondition"] = $question->usableForPrecondition();
2372  $all_questions[$row["question_id"]]["availableRelations"] = $question->getAvailableRelations();
2373  if (array_key_exists($row["question_id"], $obligatory_states))
2374  {
2375  $all_questions[$row["question_id"]]["obligatory"] = $obligatory_states[$row["question_id"]];
2376  }
2377  }
2378  }
2379  // get all questionblocks
2380  $questionblocks = array();
2381  if (count($all_questions))
2382  {
2383  $result = $ilDB->queryF("SELECT svy_qblk.*, svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst WHERE " .
2384  "svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_qblk_qst.survey_fi = %s " .
2385  "AND " . $ilDB->in('svy_qblk_qst.question_fi', array_keys($all_questions), false, 'integer'),
2386  array('integer'),
2387  array($this->getSurveyId())
2388  );
2389  while ($row = $ilDB->fetchAssoc($result))
2390  {
2391  $questionblocks[$row['question_fi']] = $row;
2392  }
2393  }
2394 
2395  foreach ($all_questions as $question_id => $row)
2396  {
2397  $constraints = $this->getConstraints($question_id);
2398  if (isset($questionblocks[$question_id]))
2399  {
2400  $all_questions[$question_id]["questionblock_title"] = $questionblocks[$question_id]['title'];
2401  $all_questions[$question_id]["questionblock_id"] = $questionblocks[$question_id]['questionblock_id'];
2402  $all_questions[$question_id]["constraints"] = $constraints;
2403  }
2404  else
2405  {
2406  $all_questions[$question_id]["questionblock_title"] = "";
2407  $all_questions[$question_id]["questionblock_id"] = "";
2408  $all_questions[$question_id]["constraints"] = $constraints;
2409  }
2410  if ($with_answers)
2411  {
2412  $answers = array();
2413  $result = $ilDB->queryF("SELECT svy_variable.*, svy_category.title FROM svy_variable, svy_category " .
2414  "WHERE svy_variable.question_fi = %s AND svy_variable.category_fi = svy_category.category_id ".
2415  "ORDER BY sequence ASC",
2416  array('integer'),
2417  array($question_id)
2418  );
2419  if ($result->numRows() > 0)
2420  {
2421  while ($data = $ilDB->fetchAssoc($result))
2422  {
2423  array_push($answers, $data["title"]);
2424  }
2425  }
2426  $all_questions[$question_id]["answers"] = $answers;
2427  }
2428  }
2429  return $all_questions;
2430  }
2431 
2438  function setObligatoryStates($obligatory_questions)
2439  {
2440  global $ilDB;
2441  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE survey_fi = %s",
2442  array('integer'),
2443  array($this->getSurveyId())
2444  );
2445  if ($result->numRows())
2446  {
2447  while ($row = $ilDB->fetchAssoc($result))
2448  {
2449  if (!array_key_exists($row["question_fi"], $obligatory_questions))
2450  {
2451  $obligatory_questions[$row["question_fi"]] = 0;
2452  }
2453  }
2454  }
2455 
2456  // set the obligatory states in the database
2457  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_oblig WHERE survey_fi = %s",
2458  array('integer'),
2459  array($this->getSurveyId())
2460  );
2461 
2462  // set the obligatory states in the database
2463  foreach ($obligatory_questions as $question_fi => $obligatory)
2464  {
2465  $next_id = $ilDB->nextId('svy_qst_oblig');
2466  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qst_oblig (question_obligatory_id, survey_fi, question_fi, " .
2467  "obligatory, tstamp) VALUES (%s, %s, %s, %s, %s)",
2468  array('integer','integer','integer','text','integer'),
2469  array($next_id, $this->getSurveyId(), $question_fi, (strlen($obligatory)) ? $obligatory : 0, time())
2470  );
2471 
2472  // #12420
2473  $ilDB->manipulate("UPDATE svy_question".
2474  " SET obligatory = ".$ilDB->quote($obligatory, "integer").
2475  " WHERE question_id = ".$ilDB->quote($question_fi, "integer"));
2476  }
2477  }
2478 
2486  {
2487  global $ilDB;
2488  $obligatory_states = array();
2489  $result = $ilDB->queryF("SELECT * FROM svy_qst_oblig WHERE survey_fi = %s",
2490  array('integer'),
2491  array($this->getSurveyId())
2492  );
2493  if ($result->numRows())
2494  {
2495  while ($row = $ilDB->fetchAssoc($result))
2496  {
2497  $obligatory_states[$row["question_fi"]] = $row["obligatory"];
2498  }
2499  }
2500  return $obligatory_states;
2501  }
2502 
2508  function &getSurveyPages()
2509  {
2510  global $ilDB;
2511  $obligatory_states =& $this->getObligatoryStates();
2512  // get questionblocks
2513  $all_questions = array();
2514  $result = $ilDB->queryF("SELECT svy_question.*, svy_qtype.type_tag, svy_svy_qst.heading FROM " .
2515  "svy_question, svy_qtype, svy_svy_qst WHERE svy_svy_qst.survey_fi = %s AND " .
2516  "svy_svy_qst.question_fi = svy_question.question_id AND svy_question.questiontype_fi = svy_qtype.questiontype_id ".
2517  "ORDER BY svy_svy_qst.sequence",
2518  array('integer'),
2519  array($this->getSurveyId())
2520  );
2521  while ($row = $ilDB->fetchAssoc($result))
2522  {
2523  $all_questions[$row["question_id"]] = $row;
2524  }
2525  // get all questionblocks
2526  $questionblocks = array();
2527  if (count($all_questions))
2528  {
2529  $result = $ilDB->queryF("SELECT svy_qblk.*, svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst ".
2530  "WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_qblk_qst.survey_fi = %s ".
2531  "AND " . $ilDB->in('svy_qblk_qst.question_fi', array_keys($all_questions), false, 'integer'),
2532  array('integer'),
2533  array($this->getSurveyId())
2534  );
2535  while ($row = $ilDB->fetchAssoc($result))
2536  {
2537  $questionblocks[$row['question_fi']] = $row;
2538  }
2539  }
2540 
2541  $all_pages = array();
2542  $pageindex = -1;
2543  $currentblock = "";
2544  foreach ($all_questions as $question_id => $row)
2545  {
2546  if (array_key_exists($question_id, $obligatory_states))
2547  {
2548  $all_questions[$question_id]["obligatory"] = $obligatory_states[$question_id];
2549  }
2550  $constraints = array();
2551  if (isset($questionblocks[$question_id]))
2552  {
2553  if (!$currentblock or ($currentblock != $questionblocks[$question_id]['questionblock_id']))
2554  {
2555  $pageindex++;
2556  }
2557  $all_questions[$question_id]['page'] = $pageindex;
2558  $all_questions[$question_id]["questionblock_title"] = $questionblocks[$question_id]['title'];
2559  $all_questions[$question_id]["questionblock_id"] = $questionblocks[$question_id]['questionblock_id'];
2560  $all_questions[$question_id]["questionblock_show_questiontext"] = $questionblocks[$question_id]['show_questiontext'];
2561  $all_questions[$question_id]["questionblock_show_blocktitle"] = $questionblocks[$question_id]['show_blocktitle'];
2562  $currentblock = $questionblocks[$question_id]['questionblock_id'];
2563  $constraints = $this->getConstraints($question_id);
2564  $all_questions[$question_id]["constraints"] = $constraints;
2565  }
2566  else
2567  {
2568  $pageindex++;
2569  $all_questions[$question_id]['page'] = $pageindex;
2570  $all_questions[$question_id]["questionblock_title"] = "";
2571  $all_questions[$question_id]["questionblock_id"] = "";
2572  $all_questions[$question_id]["questionblock_show_questiontext"] = 1;
2573  $all_questions[$question_id]["questionblock_show_blocktitle"] = 1;
2574  $currentblock = "";
2575  $constraints = $this->getConstraints($question_id);
2576  $all_questions[$question_id]["constraints"] = $constraints;
2577  }
2578  if (!isset($all_pages[$pageindex]))
2579  {
2580  $all_pages[$pageindex] = array();
2581  }
2582  array_push($all_pages[$pageindex], $all_questions[$question_id]);
2583  }
2584  // calculate position percentage for every page
2585  $max = count($all_pages);
2586  $counter = 1;
2587  foreach ($all_pages as $index => $block)
2588  {
2589  foreach ($block as $blockindex => $question)
2590  {
2591  $all_pages[$index][$blockindex]["position"] = $counter / $max;
2592  }
2593  $counter++;
2594  }
2595  return $all_pages;
2596  }
2597 
2606  function getNextPage($active_page_question_id, $direction)
2607  {
2608  $foundpage = -1;
2609  $pages =& $this->getSurveyPages();
2610  if (strcmp($active_page_question_id, "") == 0)
2611  {
2612  return $pages[0];
2613  }
2614  foreach ($pages as $key => $question_array)
2615  {
2616  foreach ($question_array as $question)
2617  {
2618  if ($active_page_question_id == $question["question_id"])
2619  {
2620  $foundpage = $key;
2621  }
2622  }
2623  }
2624  if ($foundpage == -1)
2625  {
2626  // error: page not found
2627  }
2628  else
2629  {
2630  $foundpage += $direction;
2631  if ($foundpage < 0)
2632  {
2633  return 0;
2634  }
2635  if ($foundpage >= count($pages))
2636  {
2637  return 1;
2638  }
2639  return $pages[$foundpage];
2640  }
2641  }
2642 
2649  function &getAvailableQuestionpools($use_obj_id = false, $could_be_offline = false, $showPath = FALSE, $permission = "read")
2650  {
2651  include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php";
2652  return ilObjSurveyQuestionPool::_getAvailableQuestionpools($use_obj_id, $could_be_offline, $showPath, $permission);
2653  }
2654 
2661  {
2662  global $ilDB;
2663 
2664  $result_array = array();
2665  $result = $ilDB->queryF("SELECT svy_constraint.*, svy_relation.* FROM svy_qst_constraint, svy_constraint, ".
2666  "svy_relation WHERE svy_constraint.relation_fi = svy_relation.relation_id AND ".
2667  "svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_constraint.constraint_id = %s",
2668  array('integer'),
2669  array($id)
2670  );
2671  $pc = array();
2672  if ($result->numRows())
2673  {
2674  $pc = $ilDB->fetchAssoc($result);
2675  }
2676  return $pc;
2677  }
2678 
2684  function getConstraints($question_id)
2685  {
2686  global $ilDB;
2687 
2688  $result_array = array();
2689  $result = $ilDB->queryF("SELECT svy_constraint.*, svy_relation.* FROM svy_qst_constraint, svy_constraint, svy_relation ".
2690  "WHERE svy_constraint.relation_fi = svy_relation.relation_id AND ".
2691  "svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_qst_constraint.question_fi = %s ".
2692  "AND svy_qst_constraint.survey_fi = %s",
2693  array('integer','integer'),
2694  array($question_id, $this->getSurveyId())
2695  );
2696  while ($row = $ilDB->fetchAssoc($result))
2697  {
2698  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
2699  $question_type = SurveyQuestion::_getQuestionType($row["question_fi"]);
2700  SurveyQuestion::_includeClass($question_type);
2701  $question = new $question_type();
2702  $question->loadFromDb($row["question_fi"]);
2703  $valueoutput = $question->getPreconditionValueOutput($row["value"]);
2704  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));
2705  }
2706  return $result_array;
2707  }
2708 
2715  {
2716  global $ilDB;
2717  $result_array = array();
2718  $result = $ilDB->queryF("SELECT svy_qst_constraint.question_fi as for_question, svy_constraint.*, svy_relation.* ".
2719  "FROM svy_qst_constraint, svy_constraint, svy_relation WHERE svy_constraint.relation_fi = svy_relation.relation_id ".
2720  "AND svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_qst_constraint.survey_fi = %s",
2721  array('integer'),
2722  array($survey_id)
2723  );
2724  while ($row = $ilDB->fetchAssoc($result))
2725  {
2726  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']));
2727  }
2728  return $result_array;
2729  }
2730 
2731 
2737  function &getVariables($question_id)
2738  {
2739  global $ilDB;
2740 
2741  $result_array = array();
2742  $result = $ilDB->queryF("SELECT svy_variable.*, svy_category.title FROM svy_variable LEFT JOIN ".
2743  "svy_category ON svy_variable.category_fi = svy_category.category_id WHERE svy_variable.question_fi = %s ".
2744  "ORDER BY svy_variable.sequence",
2745  array('integer'),
2746  array($question_id)
2747  );
2748  while ($row = $ilDB->fetchObject($result))
2749  {
2750  $result_array[$row->sequence] = $row;
2751  }
2752  return $result_array;
2753  }
2754 
2763  function addConstraint($if_question_id, $relation, $value, $conjunction)
2764  {
2765  global $ilDB;
2766 
2767  $next_id = $ilDB->nextId('svy_constraint');
2768  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_constraint (constraint_id, question_fi, relation_fi, value, conjunction) VALUES ".
2769  "(%s, %s, %s, %s, %s)",
2770  array('integer','integer','integer','float', 'integer'),
2771  array($next_id, $if_question_id, $relation, $value, $conjunction)
2772  );
2773  if ($affectedRows)
2774  {
2775  return $next_id;
2776  }
2777  else
2778  {
2779  return null;
2780  }
2781  }
2782 
2783 
2790  public function addConstraintToQuestion($to_question_id, $constraint_id)
2791  {
2792  global $ilDB;
2793 
2794  $next_id = $ilDB->nextId('svy_qst_constraint');
2795  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qst_constraint (question_constraint_id, survey_fi, question_fi, ".
2796  "constraint_fi) VALUES (%s, %s, %s, %s)",
2797  array('integer','integer','integer','integer'),
2798  array($next_id, $this->getSurveyId(), $to_question_id, $constraint_id)
2799  );
2800  }
2801 
2812  function updateConstraint($precondition_id, $if_question_id, $relation, $value, $conjunction)
2813  {
2814  global $ilDB;
2815  $affectedRows = $ilDB->manipulateF("UPDATE svy_constraint SET question_fi = %s, relation_fi = %s, value = %s, conjunction = %s ".
2816  "WHERE constraint_id = %s",
2817  array('integer','integer','float','integer','integer'),
2818  array($if_question_id, $relation, $value, $conjunction, $precondition_id)
2819  );
2820  }
2821 
2822  public function updateConjunctionForQuestions($questions, $conjunction)
2823  {
2824  global $ilDB;
2825  foreach ($questions as $question_id)
2826  {
2827  $affectedRows = $ilDB->manipulateF("UPDATE svy_constraint SET conjunction = %s ".
2828  "WHERE constraint_id IN (SELECT constraint_fi FROM svy_qst_constraint WHERE svy_qst_constraint.question_fi = %s)",
2829  array('integer','integer'),
2830  array($conjunction, $question_id)
2831  );
2832  }
2833  }
2834 
2840  function getAllRelations($short_as_key = false)
2841  {
2842  global $ilDB;
2843 
2844  // #7987
2845  $custom_order = array("equal", "not_equal", "less", "less_or_equal", "more", "more_or_equal");
2846  $custom_order = array_flip($custom_order);
2847 
2848  $result_array = array();
2849  $result = $ilDB->query("SELECT * FROM svy_relation");
2850  while ($row = $ilDB->fetchAssoc($result))
2851  {
2852  if ($short_as_key)
2853  {
2854  $result_array[$row["shortname"]] = array("short" => $row["shortname"], "long" => $row["longname"], "id" => $row["relation_id"], "order" => $custom_order[$row["longname"]]);
2855  }
2856  else
2857  {
2858  $result_array[$row["relation_id"]] = array("short" => $row["shortname"], "long" => $row["longname"], "order" => $custom_order[$row["longname"]]);
2859  }
2860  }
2861 
2862  $result_array = ilUtil::sortArray($result_array, "order", "ASC", true, true);
2863  foreach($result_array as $idx => $item)
2864  {
2865  unset($result_array[$idx]["order"]);
2866  }
2867 
2868  return $result_array;
2869  }
2870 
2874  public function disinviteAllUsers()
2875  {
2876  global $ilDB;
2877  $result = $ilDB->queryF("SELECT user_fi FROM svy_inv_usr WHERE survey_fi = %s",
2878  array('integer'),
2879  array($this->getSurveyId())
2880  );
2881  while ($row = $ilDB->fetchAssoc($result))
2882  {
2883  $this->disinviteUser($row['user_fi']);
2884  }
2885  }
2886 
2892  public function disinviteUser($user_id)
2893  {
2894  global $ilDB;
2895 
2896  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_inv_usr WHERE survey_fi = %s AND user_fi = %s",
2897  array('integer','integer'),
2898  array($this->getSurveyId(), $user_id)
2899  );
2900  include_once './Services/User/classes/class.ilObjUser.php';
2901  ilObjUser::_dropDesktopItem($user_id, $this->getRefId(), "svy");
2902  }
2903 
2910  function inviteUser($user_id)
2911  {
2912  global $ilDB;
2913 
2914  $result = $ilDB->queryF("SELECT user_fi FROM svy_inv_usr WHERE user_fi = %s AND survey_fi = %s",
2915  array('integer','integer'),
2916  array($user_id, $this->getSurveyId())
2917  );
2918  if ($result->numRows() < 1)
2919  {
2920  $next_id = $ilDB->nextId('svy_inv_usr');
2921  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_inv_usr (invited_user_id, survey_fi, user_fi, tstamp) " .
2922  "VALUES (%s, %s, %s, %s)",
2923  array('integer','integer','integer','integer'),
2924  array($next_id, $this->getSurveyId(), $user_id, time())
2925  );
2926  }
2927  if ($this->getInvitation() == INVITATION_ON)
2928  {
2929  include_once './Services/User/classes/class.ilObjUser.php';
2930  ilObjUser::_addDesktopItem($user_id, $this->getRefId(), "svy");
2931  }
2932  }
2933 
2940  function inviteGroup($group_id)
2941  {
2942  global $ilAccess;
2943  $invited = 0;
2944  include_once "./Modules/Group/classes/class.ilObjGroup.php";
2945  $group = new ilObjGroup($group_id);
2946  $members = $group->getGroupMemberIds();
2947  foreach ($members as $user_id)
2948  {
2949  if ($ilAccess->checkAccessOfUser($user_id, "read", "", $this->getRefId(), "svy", $this->getId()))
2950  {
2951  $this->inviteUser($user_id);
2952  if ($this->getInvitation() == INVITATION_ON)
2953  {
2954  include_once './Services/User/classes/class.ilObjUser.php';
2955  ilObjUser::_addDesktopItem($user_id, $this->getRefId(), "svy");
2956  }
2957  }
2958  }
2959  return $invited;
2960  }
2961 
2968  function inviteRole($role_id)
2969  {
2970  global $rbacreview;
2971  global $ilAccess;
2972  $invited = 0;
2973  $members = $rbacreview->assignedUsers($role_id);
2974  foreach ($members as $user_id)
2975  {
2976  if ($ilAccess->checkAccessOfUser($user_id, "read", "", $this->getRefId(), "svy", $this->getId()))
2977  {
2978  $this->inviteUser($user_id);
2979  if ($this->getInvitation() == INVITATION_ON)
2980  {
2981  include_once './Services/User/classes/class.ilObjUser.php';
2982  ilObjUser::_addDesktopItem($user_id, $this->getRefId(), "svy");
2983  }
2984  }
2985  }
2986  return $invited;
2987  }
2988 
2995  function &getInvitedUsers()
2996  {
2997  global $ilDB;
2998 
2999  $result_array = array();
3000  $result = $ilDB->queryF("SELECT user_fi FROM svy_inv_usr WHERE survey_fi = %s",
3001  array('integer'),
3002  array($this->getSurveyId())
3003  );
3004  while ($row = $ilDB->fetchAssoc($result))
3005  {
3006  array_push($result_array, $row["user_fi"]);
3007  }
3008  return $result_array;
3009  }
3010 
3018  function deleteWorkingData($question_id, $active_id)
3019  {
3020  global $ilDB;
3021 
3022  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE question_fi = %s AND active_fi = %s",
3023  array('integer','integer'),
3024  array($question_id, $active_id)
3025  );
3026  }
3027 
3036  function loadWorkingData($question_id, $active_id)
3037  {
3038  global $ilDB;
3039  $result_array = array();
3040  $result = $ilDB->queryF("SELECT * FROM svy_answer WHERE question_fi = %s AND active_fi = %s",
3041  array('integer','integer'),
3042  array($question_id, $active_id)
3043  );
3044  if ($result->numRows() >= 1)
3045  {
3046  while ($row = $ilDB->fetchAssoc($result))
3047  {
3048  array_push($result_array, $row);
3049  }
3050  return $result_array;
3051  }
3052  else
3053  {
3054  return $result_array;
3055  }
3056  }
3057 
3064  function fillSurveyForUser($user_id = ANONYMOUS_USER_ID)
3065  {
3066  global $ilDB;
3067  // create an anonymous key
3068  $anonymous_id = $this->createNewAccessCode();
3069  $this->saveUserAccessCode($user_id, $anonymous_id);
3070  // create the survey_finished dataset and set the survey finished already
3071  $active_id = $ilDB->nextId('svy_finished');
3072  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_finished (finished_id, survey_fi, user_fi, anonymous_id, state, tstamp) ".
3073  "VALUES (%s, %s, %s, %s, %s, %s)",
3074  array('integer','integer','integer','text','text','integer'),
3075  array($active_id, $this->getSurveyId(), $user_id, $anonymous_id, 1, time())
3076  );
3077  // fill the questions randomly
3078  $pages =& $this->getSurveyPages();
3079  foreach ($pages as $key => $question_array)
3080  {
3081  foreach ($question_array as $question)
3082  {
3083  // instanciate question
3084  require_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
3085  $question =& SurveyQuestion::_instanciateQuestion($question["question_id"]);
3086  $question->saveRandomData($active_id);
3087  }
3088  }
3089  }
3090 
3097  function startSurvey($user_id, $anonymous_id)
3098  {
3099  global $ilUser;
3100  global $ilDB;
3101 
3102  if ($this->getAnonymize() && (strlen($anonymous_id) == 0)) return;
3103 
3104  if (strcmp($user_id, "") == 0)
3105  {
3106  if ($user_id == ANONYMOUS_USER_ID)
3107  {
3108  $user_id = 0;
3109  }
3110  }
3111  $next_id = $ilDB->nextId('svy_finished');
3112  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_finished (finished_id, survey_fi, user_fi, anonymous_id, state, tstamp) ".
3113  "VALUES (%s, %s, %s, %s, %s, %s)",
3114  array('integer','integer','integer','text','text','integer'),
3115  array($next_id, $this->getSurveyId(), $user_id, $anonymous_id, 0, time())
3116  );
3117  return $next_id;
3118  }
3119 
3126  function finishSurvey($user_id, $anonymize_id)
3127  {
3128  global $ilDB;
3129 
3130  if ($this->getAnonymize())
3131  {
3132  $affectedRows = $ilDB->manipulateF("UPDATE svy_finished SET state = %s, user_fi = %s, tstamp = %s ".
3133  "WHERE survey_fi = %s AND anonymous_id = %s",
3134  array('text','integer','integer','integer','text'),
3135  array(1, $user_id, time(), $this->getSurveyId(), $anonymize_id)
3136  );
3137  }
3138  else
3139  {
3140  $affectedRows = $ilDB->manipulateF("UPDATE svy_finished SET state = %s, tstamp = %s WHERE survey_fi = %s AND user_fi = %s",
3141  array('text','integer','integer','integer'),
3142  array(1, time(), $this->getSurveyId(), $user_id)
3143  );
3144  }
3145  if ($this->getMailNotification())
3146  {
3147  $this->sendNotificationMail($user_id, $anonymize_id);
3148  }
3149  }
3150 
3158  function setPage($finished_id, $page_id)
3159  {
3160  global $ilDB;
3161 
3162  $affectedRows = $ilDB->manipulateF("UPDATE svy_finished SET lastpage = %s WHERE finished_id = %s",
3163  array('integer','integer'),
3164  array(($page_id) ? $page_id : 0, $finished_id)
3165  );
3166  }
3167 
3168  function sendNotificationMail($user_id, $anonymize_id)
3169  {
3170  include_once "./Services/User/classes/class.ilObjUser.php";
3171  include_once "./Services/Mail/classes/class.ilMail.php";
3172 
3173  // #12755
3174  $placeholders = array(
3175  "FIRST_NAME" => "firstname",
3176  "LAST_NAME" => "lastname",
3177  "LOGIN" => "login",
3178  // old style
3179  "firstname" => "firstname"
3180  );
3181 
3182  $mail = new ilMail(ANONYMOUS_USER_ID);
3183  $recipients = preg_split('/,/', $this->mailaddresses);
3184  foreach ($recipients as $recipient)
3185  {
3186  $messagetext = $this->mailparticipantdata;
3187  $data = ilObjUser::_getUserData(array($user_id));
3188  $data = $data[0];
3189  foreach ($placeholders as $key => $mapping)
3190  {
3191  if ($this->getAnonymize())
3192  {
3193  $messagetext = str_replace('[' . $key . ']', '', $messagetext);
3194  }
3195  else
3196  {
3197  $messagetext = str_replace('[' . $key . ']', trim($data[$mapping]), $messagetext);
3198  }
3199  }
3200  $active_id = $this->getActiveID($user_id, $anonymize_id);
3201  $messagetext .= ((strlen($messagetext)) ? "\n\n\n" : '') . $this->lng->txt('results') . "\n\n". $this->getParticipantTextResults($active_id);
3202 
3203  $mail->sendMail(
3204  $recipient, // to
3205  "", // cc
3206  "", // bcc
3207  $this->lng->txt('finished_mail_subject') . ': ' . $this->getTitle(), // subject
3208  $messagetext, // message
3209  array(), // attachments
3210  array('normal') // type
3211  );
3212  }
3213  }
3214 
3215  protected function getParticipantTextResults($active_id)
3216  {
3217  $textresult = "";
3218  $userResults =& $this->getUserSpecificResults();
3219  $questions =& $this->getSurveyQuestions(true);
3220  $questioncounter = 1;
3221  foreach ($questions as $question_id => $question_data)
3222  {
3223  $textresult .= $questioncounter++ . ". " . $question_data["title"] . "\n";
3224  $found = $userResults[$question_id][$active_id];
3225  $text = "";
3226  if (is_array($found))
3227  {
3228  $text = implode("\n", $found);
3229  }
3230  else
3231  {
3232  $text = $found;
3233  }
3234  if (strlen($text) == 0) $text = $this->lng->txt("skipped");
3235  $text = str_replace("<br />", "\n", $text);
3236  $textresult .= $text . "\n\n";
3237  }
3238  return $textresult;
3239  }
3240 
3242  {
3243  $counter = 0;
3244  $questions =& $this->getSurveyQuestions();
3245  $counter++;
3246  foreach ($questions as $data)
3247  {
3248  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
3249  $question = SurveyQuestion::_instanciateQuestion($data["question_id"]);
3250 
3251  $eval = $this->getCumulatedResults($question);
3252  }
3253  }
3254 
3262  function isAllowedToTakeMultipleSurveys($userid = "")
3263  {
3264  // #7927: special users are deprecated
3265  return false;
3266 
3267  /*
3268  $result = FALSE;
3269  if ($this->getAnonymize())
3270  {
3271  if ($this->isAccessibleWithoutCode())
3272  {
3273  if (strlen($username) == 0)
3274  {
3275  global $ilUser;
3276  $userid = $ilUser->getId();
3277  }
3278  global $ilSetting;
3279  $surveysetting = new ilSetting("survey");
3280  $allowedUsers = strlen($surveysetting->get("multiple_survey_users")) ? explode(",",$surveysetting->get("multiple_survey_users")) : array();
3281  if (in_array($userid, $allowedUsers))
3282  {
3283  $result = TRUE;
3284  }
3285  }
3286  }
3287  return $result;
3288  */
3289  }
3290 
3298  function isSurveyStarted($user_id, $anonymize_id)
3299  {
3300  global $ilDB;
3301 
3302  if ($this->getAnonymize())
3303  {
3304  if ((($user_id != ANONYMOUS_USER_ID) && sizeof($anonymize_id)) && (!($this->isAccessibleWithoutCode() && $this->isAllowedToTakeMultipleSurveys())))
3305  {
3306  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
3307  array('integer','integer'),
3308  array($this->getSurveyId(), $user_id)
3309  );
3310  }
3311  else
3312  {
3313  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s AND anonymous_id = %s",
3314  array('integer','text'),
3315  array($this->getSurveyId(), $anonymize_id)
3316  );
3317  }
3318  }
3319  else
3320  {
3321  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
3322  array('integer','integer'),
3323  array($this->getSurveyId(), $user_id)
3324  );
3325  }
3326  if ($result->numRows() == 0)
3327  {
3328  return false;
3329  }
3330  else
3331  {
3332  $row = $ilDB->fetchAssoc($result);
3333  $_SESSION["finished_id"][$this->getId()] = $row["finished_id"];
3334  return (int)$row["state"];
3335  }
3336  }
3337 
3345  function getActiveID($user_id, $anonymize_id)
3346  {
3347  global $ilDB;
3348 
3349  if ($this->getAnonymize())
3350  {
3351  if ((($user_id != ANONYMOUS_USER_ID) && (strlen($anonymize_id) == 0)) && (!($this->isAccessibleWithoutCode() && $this->isAllowedToTakeMultipleSurveys())))
3352  {
3353  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
3354  array('integer','integer'),
3355  array($this->getSurveyId(), $user_id)
3356  );
3357  }
3358  else
3359  {
3360  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s AND anonymous_id = %s",
3361  array('integer','text'),
3362  array($this->getSurveyId(), $anonymize_id)
3363  );
3364  }
3365  }
3366  else
3367  {
3368  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
3369  array('integer','integer'),
3370  array($this->getSurveyId(), $user_id)
3371  );
3372  }
3373  if ($result->numRows() == 0)
3374  {
3375  return false;
3376  }
3377  else
3378  {
3379  $row = $ilDB->fetchAssoc($result);
3380  return $row["finished_id"];
3381  }
3382  }
3383 
3391  function getLastActivePage($active_id)
3392  {
3393  global $ilDB;
3394  $result = $ilDB->queryF("SELECT lastpage FROM svy_finished WHERE finished_id = %s",
3395  array('integer'),
3396  array($active_id)
3397  );
3398  if ($result->numRows() == 0)
3399  {
3400  return "";
3401  }
3402  else
3403  {
3404  $row = $ilDB->fetchAssoc($result);
3405  return ($row["lastpage"]) ? $row["lastpage"] : '';
3406  }
3407  }
3408 
3417  function checkConstraint($constraint_data, $working_data)
3418  {
3419  if (count($working_data) == 0)
3420  {
3421  return 0;
3422  }
3423 
3424  if ((count($working_data) == 1) and (strcmp($working_data[0]["value"], "") == 0))
3425  {
3426  return 0;
3427  }
3428 
3429  $found = false;
3430  foreach ($working_data as $data)
3431  {
3432  switch ($constraint_data["short"])
3433  {
3434  case "<":
3435  if ($data["value"] < $constraint_data["value"])
3436  {
3437  $found = true;
3438  }
3439  break;
3440 
3441  case "<=":
3442  if ($data["value"] <= $constraint_data["value"])
3443  {
3444  $found = true;
3445  }
3446  break;
3447 
3448  case "=":
3449  if ($data["value"] == $constraint_data["value"])
3450  {
3451  $found = true;
3452  }
3453  break;
3454 
3455  case "<>":
3456  if ($data["value"] <> $constraint_data["value"])
3457  {
3458  $found = true;
3459  }
3460  break;
3461 
3462  case ">=":
3463  if ($data["value"] >= $constraint_data["value"])
3464  {
3465  $found = true;
3466  }
3467  break;
3468 
3469  case ">":
3470  if ($data["value"] > $constraint_data["value"])
3471  {
3472  $found = true;
3473  }
3474  break;
3475  }
3476  if ($found)
3477  {
3478  break;
3479  }
3480  }
3481 
3482  return (int)$found;
3483  }
3484 
3486  {
3487  global $ilDB;
3488 
3489  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
3490  array('integer'),
3491  array($survey_id)
3492  );
3493  return ($result->numRows()) ? true : false;
3494  }
3495 
3503  {
3504  global $ilDB, $ilLog;
3505 
3506  $users = array();
3507  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s",
3508  array('integer'),
3509  array($this->getSurveyId())
3510  );
3511  if ($result->numRows())
3512  {
3513  while ($row = $ilDB->fetchAssoc($result))
3514  {
3515  array_push($users, $row["finished_id"]);
3516  }
3517  }
3518  return $users;
3519  }
3520 
3528  {
3529  global $ilDB;
3530 
3531  $users = array();
3532  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s",
3533  array('integer'),
3534  array($this->getSurveyId())
3535  );
3536  if ($result->numRows())
3537  {
3538  while ($row = $ilDB->fetchAssoc($result))
3539  {
3540  array_push($users, $row);
3541  }
3542  }
3543  $evaluation = array();
3544  $questions =& $this->getSurveyQuestions();
3545  foreach ($questions as $question_id => $question_data)
3546  {
3547  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
3548  $question_type = SurveyQuestion::_getQuestionType($question_id);
3549  SurveyQuestion::_includeClass($question_type);
3550  $question = new $question_type();
3551  $question->loadFromDb($question_id);
3552  $data =& $question->getUserAnswers($this->getSurveyId());
3553  $evaluation[$question_id] = $data;
3554  }
3555  return $evaluation;
3556  }
3557 
3565  function getUserDataFromActiveId($active_id)
3566  {
3567  global $ilDB;
3568 
3569  $surveySetting = new ilSetting("survey");
3570  $use_anonymous_id = array_key_exists("use_anonymous_id", $_GET) ? $_GET["use_anonymous_id"] : $surveySetting->get("use_anonymous_id");
3571  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE finished_id = %s",
3572  array('integer'),
3573  array($active_id)
3574  );
3575  $row = array();
3576  $foundrows = $result->numRows();
3577  if ($foundrows)
3578  {
3579  $row = $ilDB->fetchAssoc($result);
3580  }
3581  $name = ($use_anonymous_id) ? $row["anonymous_id"] : $this->lng->txt("anonymous");
3582  $userdata = array(
3583  "fullname" => $name,
3584  "sortname" => $name,
3585  "firstname" => "",
3586  "lastname" => "",
3587  "login" => "",
3588  "gender" => "",
3589  "active_id" => "$active_id"
3590  );
3591  if ($foundrows)
3592  {
3593  if (($row["user_fi"] > 0) && ($row["user_fi"] != ANONYMOUS_USER_ID) && ($this->getAnonymize() == 0))
3594  {
3595  include_once './Services/User/classes/class.ilObjUser.php';
3596  if (strlen(ilObjUser::_lookupLogin($row["user_fi"])) == 0)
3597  {
3598  $userdata["fullname"] = $userdata["sortname"] = $this->lng->txt("deleted_user");
3599  }
3600  else
3601  {
3602  $user = new ilObjUser($row["user_fi"]);
3603  $userdata["fullname"] = $user->getFullname();
3604  $gender = $user->getGender();
3605  if (strlen($gender) == 1) $gender = $this->lng->txt("gender_$gender");
3606  $userdata["gender"] = $gender;
3607  $userdata["firstname"] = $user->getFirstname();
3608  $userdata["lastname"] = $user->getLastname();
3609  $userdata["sortname"] = $user->getLastname() . ", " . $user->getFirstname();
3610  $userdata["login"] = $user->getLogin();
3611  }
3612  }
3613  }
3614  return $userdata;
3615  }
3616 
3626  function &getEvaluationByUser($questions, $active_id)
3627  {
3628  global $ilDB;
3629 
3630  // collect all answers
3631  $answers = array();
3632  $result = $ilDB->queryF("SELECT * FROM svy_answer WHERE active_fi = %s",
3633  array('integer'),
3634  array($active_id)
3635  );
3636  while ($row = $ilDB->fetchAssoc($result))
3637  {
3638  if (!is_array($answers[$row["question_fi"]]))
3639  {
3640  $answers[$row["question_fi"]] = array();
3641  }
3642  array_push($answers[$row["question_fi"]], $row);
3643  }
3644  $userdata = $this->getUserDataFromActiveId($active_id);
3645  $resultset = array(
3646  "name" => $userdata["fullname"],
3647  "login" => $userdata["login"],
3648  "gender" => $userdata["gender"],
3649  "answers" => array()
3650  );
3651  foreach ($questions as $key => $question)
3652  {
3653  if (array_key_exists($key, $answers))
3654  {
3655  $resultset["answers"][$key] = $answers[$key];
3656  }
3657  else
3658  {
3659  $resultset["answers"][$key] = array();
3660  }
3661  sort($resultset["answers"][$key]);
3662  }
3663  return $resultset;
3664  }
3665 
3674  function getCumulatedResults(&$question)
3675  {
3676  global $ilDB;
3677 
3678  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
3679  array('integer'),
3680  array($this->getSurveyId())
3681  );
3682  $nr_of_users = $result->numRows();
3683 
3684  $result_array =& $question->getCumulatedResults($this->getSurveyId(), $nr_of_users);
3685  return $result_array;
3686  }
3687 
3696  {
3697  global $ilDB;
3698 
3699  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
3700  array('integer'),
3701  array($survey_id)
3702  );
3703  return $result->numRows();
3704  }
3705 
3706  function &getQuestions($question_ids)
3707  {
3708  global $ilDB;
3709 
3710  $result_array = array();
3711  $result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag FROM svy_question, svy_qtype WHERE ".
3712  "svy_question.questiontype_fi = svy_qtype.questiontype_id AND svy_question.tstamp > 0 AND ".
3713  $ilDB->in('svy_question.question_id', $question_ids, false, 'integer'));
3714  while ($row = $ilDB->fetchAssoc($result))
3715  {
3716  array_push($result_array, $row);
3717  }
3718  return $result_array;
3719  }
3720 
3726  function getQuestionsTable($arrFilter)
3727  {
3728  global $ilUser;
3729  global $ilDB;
3730  $where = "";
3731  if (is_array($arrFilter))
3732  {
3733  if (array_key_exists('title', $arrFilter) && strlen($arrFilter['title']))
3734  {
3735  $where .= " AND " . $ilDB->like('svy_question.title', 'text', "%%" . $arrFilter['title'] . "%%");
3736  }
3737  if (array_key_exists('description', $arrFilter) && strlen($arrFilter['description']))
3738  {
3739  $where .= " AND " . $ilDB->like('svy_question.description', 'text', "%%" . $arrFilter['description'] . "%%");
3740  }
3741  if (array_key_exists('author', $arrFilter) && strlen($arrFilter['author']))
3742  {
3743  $where .= " AND " . $ilDB->like('svy_question.author', 'text', "%%" . $arrFilter['author'] . "%%");
3744  }
3745  if (array_key_exists('type', $arrFilter) && strlen($arrFilter['type']))
3746  {
3747  $where .= " AND svy_qtype.type_tag = " . $ilDB->quote($arrFilter['type'], 'text');
3748  }
3749  if (array_key_exists('spl', $arrFilter) && strlen($arrFilter['spl']))
3750  {
3751  $where .= " AND svy_question.obj_fi = " . $ilDB->quote($arrFilter['spl'], 'integer');
3752  }
3753  }
3754 
3755  $spls =& $this->getAvailableQuestionpools($use_obj_id = TRUE, $could_be_offline = FALSE, $showPath = FALSE);
3756  $forbidden = "";
3757  $forbidden = " AND " . $ilDB->in('svy_question.obj_fi', array_keys($spls), false, 'integer');
3758  $forbidden .= " AND svy_question.complete = " . $ilDB->quote("1", 'text');
3759  $existing = "";
3760  $existing_questions =& $this->getExistingQuestions();
3761  if (count($existing_questions))
3762  {
3763  $existing = " AND " . $ilDB->in('svy_question.question_id', $existing_questions, true, 'integer');
3764  }
3765 
3766  include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php";
3768 
3769  $query_result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag, svy_qtype.plugin, object_reference.ref_id".
3770  " FROM svy_question, svy_qtype, object_reference".
3771  " WHERE svy_question.original_id IS NULL".$forbidden.$existing.
3772  " AND svy_question.obj_fi = object_reference.obj_id AND svy_question.tstamp > 0".
3773  " AND svy_question.questiontype_fi = svy_qtype.questiontype_id " . $where);
3774 
3775  $rows = array();
3776  if ($query_result->numRows())
3777  {
3778  while ($row = $ilDB->fetchAssoc($query_result))
3779  {
3780  if (array_key_exists('spl_txt', $arrFilter) && strlen($arrFilter['spl_txt']))
3781  {
3782  if(!stristr($spls[$row["obj_fi"]], $arrFilter['spl_txt']))
3783  {
3784  continue;
3785  }
3786  }
3787 
3788  $row['ttype'] = $trans[$row['type_tag']];
3789  if ($row["plugin"])
3790  {
3791  if ($this->isPluginActive($row["type_tag"]))
3792  {
3793  array_push($rows, $row);
3794  }
3795  }
3796  else
3797  {
3798  array_push($rows, $row);
3799  }
3800  }
3801  }
3802  return $rows;
3803  }
3804 
3810  function getQuestionblocksTable($arrFilter)
3811  {
3812  global $ilUser, $ilDB;
3813 
3814  $where = "";
3815  if (is_array($arrFilter))
3816  {
3817  if (array_key_exists('title', $arrFilter) && strlen($arrFilter['title']))
3818  {
3819  $where .= " AND " . $ilDB->like('svy_qblk.title', 'text', "%%" . $arrFilter['title'] . "%%");
3820  }
3821  }
3822 
3823  $query_result = $ilDB->query("SELECT svy_qblk.*, svy_svy.obj_fi FROM svy_qblk , svy_qblk_qst, svy_svy WHERE ".
3824  "svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_svy.survey_id = svy_qblk_qst.survey_fi ".
3825  "$where GROUP BY svy_qblk.questionblock_id, svy_qblk.title, svy_qblk.show_questiontext, svy_qblk.show_blocktitle, ".
3826  "svy_qblk.owner_fi, svy_qblk.tstamp, svy_svy.obj_fi");
3827  $rows = array();
3828  if ($query_result->numRows())
3829  {
3830  $survey_ref_ids = ilUtil::_getObjectsByOperations("svy", "write");
3831  $surveytitles = array();
3832  foreach ($survey_ref_ids as $survey_ref_id)
3833  {
3834  $survey_id = ilObject::_lookupObjId($survey_ref_id);
3835  $surveytitles[$survey_id] = ilObject::_lookupTitle($survey_id);
3836  }
3837  while ($row = $ilDB->fetchAssoc($query_result))
3838  {
3839  $questions_array =& $this->getQuestionblockQuestions($row["questionblock_id"]);
3840  $counter = 1;
3841  foreach ($questions_array as $key => $value)
3842  {
3843  $questions_array[$key] = "$counter. $value";
3844  $counter++;
3845  }
3846  if (strlen($surveytitles[$row["obj_fi"]])) // only questionpools which are not in trash
3847  {
3848  $rows[$row["questionblock_id"]] = array(
3849  "questionblock_id" => $row["questionblock_id"],
3850  "title" => $row["title"],
3851  "svy" => $surveytitles[$row["obj_fi"]],
3852  "contains" => join($questions_array, ", "),
3853  "owner" => $row["owner_fi"]
3854  );
3855  }
3856  }
3857  }
3858  return $rows;
3859  }
3860 
3867  function toXML()
3868  {
3869  include_once("./Services/Xml/classes/class.ilXmlWriter.php");
3870  $a_xml_writer = new ilXmlWriter;
3871  // set xml header
3872  $a_xml_writer->xmlHeader();
3873  $attrs = array(
3874  "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
3875  "xsi:noNamespaceSchemaLocation" => "http://www.ilias.de/download/xsd/ilias_survey_4_2.xsd"
3876  );
3877  $a_xml_writer->xmlStartTag("surveyobject", $attrs);
3878  $attrs = array(
3879  "id" => $this->getSurveyId(),
3880  "title" => $this->getTitle()
3881  );
3882  $a_xml_writer->xmlStartTag("survey", $attrs);
3883 
3884  $a_xml_writer->xmlElement("description", NULL, $this->getDescription());
3885  $a_xml_writer->xmlElement("author", NULL, $this->getAuthor());
3886  $a_xml_writer->xmlStartTag("objectives");
3887  $attrs = array(
3888  "label" => "introduction"
3889  );
3890  $this->addMaterialTag($a_xml_writer, $this->getIntroduction(), TRUE, TRUE, $attrs);
3891  $attrs = array(
3892  "label" => "outro"
3893  );
3894  $this->addMaterialTag($a_xml_writer, $this->getOutro(), TRUE, TRUE, $attrs);
3895  $a_xml_writer->xmlEndTag("objectives");
3896 
3897  if ($this->getAnonymize())
3898  {
3899  $attribs = array("enabled" => "1");
3900  }
3901  else
3902  {
3903  $attribs = array("enabled" => "0");
3904  }
3905  $a_xml_writer->xmlElement("anonymisation", $attribs);
3906  $a_xml_writer->xmlStartTag("restrictions");
3907  if ($this->getAnonymize() == 2)
3908  {
3909  $attribs = array("type" => "free");
3910  }
3911  else
3912  {
3913  $attribs = array("type" => "restricted");
3914  }
3915  $a_xml_writer->xmlElement("access", $attribs);
3916  if ($this->getStartDateEnabled())
3917  {
3918  $attrs = array("type" => "date");
3919  $a_xml_writer->xmlElement("startingtime", $attrs, sprintf("%04d-%02d-%02dT%02d:%02d:00", $this->getStartYear(), $this->getStartMonth(), $this->getStartDay(), $this->getStartHour(), $this->getStartMinute()));
3920  }
3921  if ($this->getEndDateEnabled())
3922  {
3923  $attrs = array("type" => "date");
3924  $a_xml_writer->xmlElement("endingtime", $attrs, sprintf("%04d-%02d-%02dT%02d:%02d:00", $this->getEndYear(), $this->getEndMonth(), $this->getEndDay(), $this->getEndHour(), $this->getEndMinute()));
3925  }
3926  $a_xml_writer->xmlEndTag("restrictions");
3927 
3928  // constraints
3929  $pages =& $this->getSurveyPages();
3930  $hasconstraints = FALSE;
3931  foreach ($pages as $question_array)
3932  {
3933  foreach ($question_array as $question)
3934  {
3935  if (count($question["constraints"]))
3936  {
3937  $hasconstraints = TRUE;
3938  }
3939  }
3940  }
3941 
3942  if ($hasconstraints)
3943  {
3944  $a_xml_writer->xmlStartTag("constraints");
3945  foreach ($pages as $question_array)
3946  {
3947  foreach ($question_array as $question)
3948  {
3949  if (count($question["constraints"]))
3950  {
3951  // found constraints
3952  foreach ($question["constraints"] as $constraint)
3953  {
3954  $attribs = array(
3955  "sourceref" => $question["question_id"],
3956  "destref" => $constraint["question"],
3957  "relation" => $constraint["short"],
3958  "value" => $constraint["value"],
3959  "conjunction" => $constraint["conjunction"]
3960  );
3961  $a_xml_writer->xmlElement("constraint", $attribs);
3962  }
3963  }
3964  }
3965  }
3966  $a_xml_writer->xmlEndTag("constraints");
3967  }
3968 
3969  // add the rest of the preferences in qtimetadata tags, because there is no correspondent definition in QTI
3970  $a_xml_writer->xmlStartTag("metadata");
3971 
3972  $a_xml_writer->xmlStartTag("metadatafield");
3973  $a_xml_writer->xmlElement("fieldlabel", NULL, "evaluation_access");
3974  $a_xml_writer->xmlElement("fieldentry", NULL, $this->getEvaluationAccess());
3975  $a_xml_writer->xmlEndTag("metadatafield");
3976 
3977  $a_xml_writer->xmlStartTag("metadatafield");
3978  $a_xml_writer->xmlElement("fieldlabel", NULL, "status");
3979  $a_xml_writer->xmlElement("fieldentry", NULL, $this->getStatus());
3980  $a_xml_writer->xmlEndTag("metadatafield");
3981 
3982  $a_xml_writer->xmlStartTag("metadatafield");
3983  $a_xml_writer->xmlElement("fieldlabel", NULL, "display_question_titles");
3984  $a_xml_writer->xmlElement("fieldentry", NULL, $this->getShowQuestionTitles());
3985  $a_xml_writer->xmlEndTag("metadatafield");
3986 
3987  $a_xml_writer->xmlStartTag("metadatafield");
3988  $a_xml_writer->xmlElement("fieldlabel", NULL, "SCORM");
3989  include_once "./Services/MetaData/classes/class.ilMD.php";
3990  $md = new ilMD($this->getId(),0, $this->getType());
3991  $writer = new ilXmlWriter();
3992  $md->toXml($writer);
3993  $metadata = $writer->xmlDumpMem();
3994  $a_xml_writer->xmlElement("fieldentry", NULL, $metadata);
3995  $a_xml_writer->xmlEndTag("metadatafield");
3996 
3997  $a_xml_writer->xmlEndTag("metadata");
3998  $a_xml_writer->xmlEndTag("survey");
3999 
4000  $attribs = array("id" => $this->getId());
4001  $a_xml_writer->xmlStartTag("surveyquestions", $attribs);
4002  // add questionblock descriptions
4003  $obligatory_states =& $this->getObligatoryStates();
4004  foreach ($pages as $question_array)
4005  {
4006  if (count($question_array) > 1)
4007  {
4008  $attribs = array("id" => $question_array[0]["question_id"]);
4009  $attribs = array("showQuestiontext" => $question_array[0]["questionblock_show_questiontext"],
4010  "showBlocktitle" => $question_array[0]["questionblock_show_blocktitle"]);
4011  $a_xml_writer->xmlStartTag("questionblock", $attribs);
4012  if (strlen($question_array[0]["questionblock_title"]))
4013  {
4014  $a_xml_writer->xmlElement("questionblocktitle", NULL, $question_array[0]["questionblock_title"]);
4015  }
4016  }
4017  foreach ($question_array as $question)
4018  {
4019  if (strlen($question["heading"]))
4020  {
4021  $a_xml_writer->xmlElement("textblock", NULL, $question["heading"]);
4022  }
4023  $questionObject =& $this->_instanciateQuestion($question["question_id"]);
4024  if ($questionObject !== FALSE) $questionObject->insertXML($a_xml_writer, FALSE, $obligatory_states[$question["question_id"]]);
4025  }
4026  if (count($question_array) > 1)
4027  {
4028  $a_xml_writer->xmlEndTag("questionblock");
4029  }
4030  }
4031 
4032  $a_xml_writer->xmlEndTag("surveyquestions");
4033  $a_xml_writer->xmlEndTag("surveyobject");
4034  $xml = $a_xml_writer->xmlDumpMem(FALSE);
4035  return $xml;
4036  }
4037 
4045  function &_instanciateQuestion($question_id)
4046  {
4047  if ($question_id < 1) return FALSE;
4048  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
4049  $question_type = SurveyQuestion::_getQuestionType($question_id);
4050  if (strlen($question_type) == 0) return FALSE;
4051  SurveyQuestion::_includeClass($question_type);
4052  $question = new $question_type();
4053  $question->loadFromDb($question_id);
4054  return $question;
4055  }
4056 
4063  function locateImportFiles($a_dir)
4064  {
4065  if (!is_dir($a_dir) || is_int(strpos($a_dir, "..")))
4066  {
4067  return;
4068  }
4069  $importDirectory = "";
4070  $xmlFile = "";
4071 
4072  $current_dir = opendir($a_dir);
4073  $files = array();
4074  while($entryname = readdir($current_dir))
4075  {
4076  $files[] = $entryname;
4077  }
4078 
4079  foreach($files as $file)
4080  {
4081  if(is_dir($a_dir."/".$file) and ($file != "." and $file!=".."))
4082  {
4083  // found directory created by zip
4084  $importDirectory = $a_dir."/".$file;
4085  }
4086  }
4087  closedir($current_dir);
4088  if (strlen($importDirectory))
4089  {
4090  // find the xml file
4091  $current_dir = opendir($importDirectory);
4092  $files = array();
4093  while($entryname = readdir($current_dir))
4094  {
4095  $files[] = $entryname;
4096  }
4097  foreach($files as $file)
4098  {
4099  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)))
4100  {
4101  // found xml file
4102  $xmlFile = $importDirectory."/".$file;
4103  }
4104  }
4105  }
4106  return array("dir" => $importDirectory, "xml" => $xmlFile);
4107  }
4108 
4115  function importObject($file_info, $svy_qpl_id)
4116  {
4117  if ($svy_qpl_id < 1) $svy_qpl_id = -1;
4118  // check if file was uploaded
4119  $source = $file_info["tmp_name"];
4120  $error = "";
4121  if (($source == 'none') || (!$source) || $file_info["error"] > UPLOAD_ERR_OK)
4122  {
4123  $error = $this->lng->txt("import_no_file_selected");
4124  }
4125  // check correct file type
4126  $isXml = FALSE;
4127  $isZip = FALSE;
4128  if ((strcmp($file_info["type"], "text/xml") == 0) || (strcmp($file_info["type"], "application/xml") == 0))
4129  {
4130  $isXml = TRUE;
4131  }
4132  // too many different mime-types, so we use the suffix
4133  $suffix = pathinfo($file_info["name"]);
4134  if (strcmp(strtolower($suffix["extension"]), "zip") == 0)
4135  {
4136  $isZip = TRUE;
4137  }
4138  if (!$isXml && !$isZip)
4139  {
4140  $error = $this->lng->txt("import_wrong_file_type");
4141  global $ilLog;
4142  $ilLog->write("Survey: Import error. Filetype was \"" . $file_info["type"] ."\"");
4143  }
4144  if (strlen($error) == 0)
4145  {
4146  // import file as a survey
4147  $import_dir = $this->getImportDirectory();
4148  $import_subdir = "";
4149  $importfile = "";
4150  include_once "./Services/Utilities/classes/class.ilUtil.php";
4151  if ($isZip)
4152  {
4153  $importfile = $import_dir."/".$file_info["name"];
4154  ilUtil::moveUploadedFile($source, $file_info["name"], $importfile);
4155  ilUtil::unzip($importfile);
4156  $found = $this->locateImportFiles($import_dir);
4157  if (!((strlen($found["dir"]) > 0) && (strlen($found["xml"]) > 0)))
4158  {
4159  $error = $this->lng->txt("wrong_import_file_structure");
4160  return $error;
4161  }
4162  $importfile = $found["xml"];
4163  $import_subdir = $found["dir"];
4164  }
4165  else
4166  {
4167  $importfile = tempnam($import_dir, "survey_import");
4168  ilUtil::moveUploadedFile($source, $file_info["name"], $importfile);
4169  }
4170  $fh = fopen($importfile, "r");
4171  if (!$fh)
4172  {
4173  $error = $this->lng->txt("import_error_opening_file");
4174  return $error;
4175  }
4176  $xml = fread($fh, filesize($importfile));
4177  $result = fclose($fh);
4178  if (!$result)
4179  {
4180  $error = $this->lng->txt("import_error_closing_file");
4181  return $error;
4182  }
4183 
4184  unset($_SESSION["import_mob_xhtml"]);
4185  if (strpos($xml, "questestinterop"))
4186  {
4187  include_once "./Services/Survey/classes/class.SurveyImportParserPre38.php";
4188  $import = new SurveyImportParserPre38($svy_qpl_id, "", TRUE);
4189  $import->setSurveyObject($this);
4190  $import->setXMLContent($xml);
4191  $import->startParsing();
4192  }
4193  else
4194  {
4195  include_once "./Services/Survey/classes/class.SurveyImportParser.php";
4196  $import = new SurveyImportParser($svy_qpl_id, "", TRUE);
4197  $import->setSurveyObject($this);
4198  $import->setXMLContent($xml);
4199  $import->startParsing();
4200  }
4201 
4202  if (is_array($_SESSION["import_mob_xhtml"]))
4203  {
4204  include_once "./Services/MediaObjects/classes/class.ilObjMediaObject.php";
4205  include_once "./Services/RTE/classes/class.ilRTE.php";
4206  include_once "./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php";
4207  foreach ($_SESSION["import_mob_xhtml"] as $mob)
4208  {
4209  $importfile = $import_subdir . "/" . $mob["uri"];
4210  if (file_exists($importfile))
4211  {
4212  $media_object =& ilObjMediaObject::_saveTempFileAsMediaObject(basename($importfile), $importfile, FALSE);
4213  ilObjMediaObject::_saveUsage($media_object->getId(), "svy:html", $this->getId());
4214  $this->setIntroduction(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $this->getIntroduction()));
4215  $this->setOutro(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $this->getOutro()));
4216  }
4217  else
4218  {
4219  global $ilLog;
4220  $ilLog->write("Error: Could not open XHTML mob file for test introduction during test import. File $importfile does not exist!");
4221  }
4222  }
4225  $this->saveToDb();
4226  }
4227 
4228  // delete import directory
4230  }
4231  return $error;
4232  }
4233 
4242  public function cloneObject($a_target_id,$a_copy_id = 0)
4243  {
4244  global $ilDB;
4245 
4246  $this->loadFromDb();
4247 
4248  // Copy settings
4249  $newObj = parent::cloneObject($a_target_id,$a_copy_id);
4250  $this->cloneMetaData($newObj);
4251  $newObj->updateMetaData();
4252 
4253  $newObj->setAuthor($this->getAuthor());
4254  $newObj->setIntroduction($this->getIntroduction());
4255  $newObj->setOutro($this->getOutro());
4256  $newObj->setStatus($this->getStatus());
4257  $newObj->setEvaluationAccess($this->getEvaluationAccess());
4258  $newObj->setStartDate($this->getStartDate());
4259  $newObj->setStartDateEnabled($this->getStartDateEnabled());
4260  $newObj->setEndDate($this->getEndDate());
4261  $newObj->setEndDateEnabled($this->getEndDateEnabled());
4262  $newObj->setInvitation($this->getInvitation());
4263  $newObj->setInvitationMode($this->getInvitationMode());
4264  $newObj->setAnonymize($this->getAnonymize());
4265  $newObj->setShowQuestionTitles($this->getShowQuestionTitles());
4266  $newObj->setTemplate($this->getTemplate());
4267 
4268 
4269  $question_pointer = array();
4270  // clone the questions
4271  $mapping = array();
4272  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
4273  foreach ($this->questions as $key => $question_id)
4274  {
4275  $question = ilObjSurvey::_instanciateQuestion($question_id);
4276  if($question) // #10824
4277  {
4278  $question->id = -1;
4279  $original_id = SurveyQuestion::_getOriginalId($question_id);
4280  $question->saveToDb($original_id);
4281  $newObj->questions[$key] = $question->getId();
4282  $question_pointer[$question_id] = $question->getId();
4283  $mapping[$question_id] = $question->getId();
4284  }
4285  }
4286 
4287  $newObj->saveToDb();
4288  $newObj->cloneTextblocks($mapping);
4289 
4290  // clone the questionblocks
4291  $questionblocks = array();
4292  $questionblock_questions = array();
4293  $result = $ilDB->queryF("SELECT * FROM svy_qblk_qst WHERE survey_fi = %s",
4294  array('integer'),
4295  array($this->getSurveyId())
4296  );
4297  if ($result->numRows() > 0)
4298  {
4299  while ($row = $ilDB->fetchAssoc($result))
4300  {
4301  array_push($questionblock_questions, $row);
4302  $questionblocks[$row["questionblock_fi"]] = $row["questionblock_fi"];
4303  }
4304  }
4305  // create new questionblocks
4306  foreach ($questionblocks as $key => $value)
4307  {
4308  $questionblock = ilObjSurvey::_getQuestionblock($key);
4309  $questionblock_id = ilObjSurvey::_addQuestionblock($questionblock["title"], $questionblock["owner_fi"]);
4310  $questionblocks[$key] = $questionblock_id;
4311  }
4312  // create new questionblock questions
4313  foreach ($questionblock_questions as $key => $value)
4314  {
4315  if($questionblocks[$value["questionblock_fi"]] &&
4316  $question_pointer[$value["question_fi"]])
4317  {
4318  $next_id = $ilDB->nextId('svy_qblk_qst');
4319  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, question_fi) ".
4320  "VALUES (%s, %s, %s, %s)",
4321  array('integer','integer','integer','integer'),
4322  array($next_id, $newObj->getSurveyId(), $questionblocks[$value["questionblock_fi"]], $question_pointer[$value["question_fi"]])
4323  );
4324  }
4325  }
4326 
4327  // clone the constraints
4328  $constraints = ilObjSurvey::_getConstraints($this->getSurveyId());
4329  $newConstraints = array();
4330  foreach ($constraints as $key => $constraint)
4331  {
4332  if ($question_pointer[$constraint["for_question"]] &&
4333  $question_pointer[$constraint["question"]])
4334  {
4335  if (!array_key_exists($constraint['id'], $newConstraints))
4336  {
4337  $constraint_id = $newObj->addConstraint($question_pointer[$constraint["question"]], $constraint["relation_id"], $constraint["value"], $constraint['conjunction']);
4338  $newConstraints[$constraint['id']] = $constraint_id;
4339  }
4340  $newObj->addConstraintToQuestion($question_pointer[$constraint["for_question"]], $newConstraints[$constraint['id']]);
4341  }
4342  }
4343 
4344  // clone the obligatory states
4345  $result = $ilDB->queryF("SELECT * FROM svy_qst_oblig WHERE survey_fi = %s",
4346  array('integer'),
4347  array($this->getSurveyId())
4348  );
4349  if ($result->numRows() > 0)
4350  {
4351  while ($row = $ilDB->fetchAssoc($result))
4352  {
4353  if($question_pointer[$row["question_fi"]])
4354  {
4355  $next_id = $ilDB->nextId('svy_qst_oblig');
4356  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qst_oblig (question_obligatory_id, survey_fi, question_fi, ".
4357  "obligatory, tstamp) VALUES (%s, %s, %s, %s, %s)",
4358  array('integer','integer','integer','text','integer'),
4359  array($next_id, $newObj->getSurveyId(), $question_pointer[$row["question_fi"]], $row["obligatory"], time())
4360  );
4361  }
4362  }
4363  }
4364  return $newObj;
4365  }
4366 
4367  function getTextblock($question_id)
4368  {
4369  global $ilDB;
4370  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE question_fi = %s",
4371  array('integer'),
4372  array($question_id)
4373  );
4374  if ($result->numRows())
4375  {
4376  $row = $ilDB->fetchAssoc($result);
4377  return $row["heading"];
4378  }
4379  else
4380  {
4381  return "";
4382  }
4383  }
4384 
4390  function cloneTextblocks($mapping)
4391  {
4392  foreach ($mapping as $original_id => $new_id)
4393  {
4394  $textblock = $this->getTextblock($original_id);
4395  include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php";
4396  $this->saveHeading(ilUtil::stripSlashes($textblock, TRUE, ilObjAdvancedEditing::_getUsedHTMLTagsAsString("survey")), $new_id);
4397  }
4398  }
4399 
4406  {
4407  include_once "./Services/Utilities/classes/class.ilUtil.php";
4408  $svy_data_dir = ilUtil::getDataDir()."/svy_data";
4409  ilUtil::makeDir($svy_data_dir);
4410  if(!is_writable($svy_data_dir))
4411  {
4412  $this->ilias->raiseError("Survey Data Directory (".$svy_data_dir
4413  .") not writeable.",$this->ilias->error_obj->FATAL);
4414  }
4415 
4416  // create learning module directory (data_dir/lm_data/lm_<id>)
4417  $svy_dir = $svy_data_dir."/svy_".$this->getId();
4418  ilUtil::makeDir($svy_dir);
4419  if(!@is_dir($svy_dir))
4420  {
4421  $this->ilias->raiseError("Creation of Survey Directory failed.",$this->ilias->error_obj->FATAL);
4422  }
4423  // create Export subdirectory (data_dir/lm_data/lm_<id>/Export)
4424  $export_dir = $svy_dir."/export";
4425  ilUtil::makeDir($export_dir);
4426  if(!@is_dir($export_dir))
4427  {
4428  $this->ilias->raiseError("Creation of Export Directory failed.",$this->ilias->error_obj->FATAL);
4429  }
4430  }
4431 
4436  {
4437  include_once "./Services/Utilities/classes/class.ilUtil.php";
4438  $export_dir = ilUtil::getDataDir()."/svy_data"."/svy_".$this->getId()."/export";
4439 
4440  return $export_dir;
4441  }
4442 
4447  {
4448  // quit if import dir not available
4449  if (!@is_dir($dir) or
4450  !is_writeable($dir))
4451  {
4452  return array();
4453  }
4454 
4455  // open directory
4456  $dir = dir($dir);
4457 
4458  // initialize array
4459  $file = array();
4460 
4461  // get files and save the in the array
4462  while ($entry = $dir->read())
4463  {
4464  if ($entry != "." && $entry != ".." && ereg("^[0-9]{10}_{2}[0-9]+_{2}(svy_)*[0-9]+\.[a-z]{1,3}\$", $entry))
4465  {
4466  $file[] = $entry;
4467  }
4468  }
4469 
4470  // close import directory
4471  $dir->close();
4472  // sort files
4473  sort ($file);
4474  reset ($file);
4475 
4476  return $file;
4477  }
4478 
4485  {
4486  include_once "./Services/Utilities/classes/class.ilUtil.php";
4487  $svy_data_dir = ilUtil::getDataDir()."/svy_data";
4488  ilUtil::makeDir($svy_data_dir);
4489 
4490  if(!is_writable($svy_data_dir))
4491  {
4492  $this->ilias->raiseError("Survey Data Directory (".$svy_data_dir
4493  .") not writeable.",$this->ilias->error_obj->FATAL);
4494  }
4495 
4496  // create test directory (data_dir/svy_data/svy_<id>)
4497  $svy_dir = $svy_data_dir."/svy_".$this->getId();
4498  ilUtil::makeDir($svy_dir);
4499  if(!@is_dir($svy_dir))
4500  {
4501  $this->ilias->raiseError("Creation of Survey Directory failed.",$this->ilias->error_obj->FATAL);
4502  }
4503 
4504  // create import subdirectory (data_dir/svy_data/svy_<id>/import)
4505  $import_dir = $svy_dir."/import";
4506  ilUtil::makeDir($import_dir);
4507  if(!@is_dir($import_dir))
4508  {
4509  $this->ilias->raiseError("Creation of Import Directory failed.",$this->ilias->error_obj->FATAL);
4510  }
4511  }
4512 
4517  {
4518  include_once "./Services/Utilities/classes/class.ilUtil.php";
4519  $import_dir = ilUtil::getDataDir()."/svy_data".
4520  "/svy_".$this->getId()."/import";
4521  if (!is_dir($import_dir))
4522  {
4523  ilUtil::makeDirParents($import_dir);
4524  }
4525  if(@is_dir($import_dir))
4526  {
4527  return $import_dir;
4528  }
4529  else
4530  {
4531  return false;
4532  }
4533  }
4534 
4535  function saveHeading($heading = "", $insertbefore)
4536  {
4537  global $ilDB;
4538  if ($heading)
4539  {
4540  $affectedRows = $ilDB->manipulateF("UPDATE svy_svy_qst SET heading=%s WHERE survey_fi=%s AND question_fi=%s",
4541  array('text','integer','integer'),
4542  array($heading, $this->getSurveyId(), $insertbefore)
4543  );
4544  }
4545  else
4546  {
4547  $affectedRows = $ilDB->manipulateF("UPDATE svy_svy_qst SET heading=%s WHERE survey_fi=%s AND question_fi=%s",
4548  array('text','integer','integer'),
4549  array(NULL, $this->getSurveyId(), $insertbefore)
4550  );
4551  }
4552  }
4553 
4554  function isAnonymousKey($key)
4555  {
4556  global $ilDB;
4557 
4558  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_anonymous WHERE survey_key = %s AND survey_fi = %s",
4559  array('text','integer'),
4560  array($key, $this->getSurveyId())
4561  );
4562  return ($result->numRows() == 1) ? true : false;
4563  }
4564 
4565  function getUserSurveyCode($user_id)
4566  {
4567  global $ilDB;
4568 
4569  if (($user_id == ANONYMOUS_USER_ID) || (($this->isAccessibleWithoutCode() && $this->isAllowedToTakeMultipleSurveys()))) return "";
4570  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
4571  array('integer','integer'),
4572  array($this->getSurveyId(), $user_id)
4573  );
4574  if ($result->numRows() == 1)
4575  {
4576  $row = $ilDB->fetchAssoc($result);
4577  return $row["anonymous_id"];
4578  }
4579  else
4580  {
4581  return "";
4582  }
4583  }
4584 
4586  {
4587  global $ilDB;
4588 
4589  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE anonymous_id = %s AND survey_fi = %s",
4590  array('text','integer'),
4591  array($key, $this->getSurveyId())
4592  );
4593  return ($result->numRows() == 1) ? true : false;
4594  }
4595 
4596  function checkSurveyCode($code)
4597  {
4598  if ($this->isAnonymousKey($code))
4599  {
4600  if ($this->isSurveyStarted("", $code) == 1)
4601  {
4602  return false;
4603  }
4604  else
4605  {
4606  return true;
4607  }
4608  }
4609  else
4610  {
4611  return false;
4612  }
4613  }
4614 
4622  {
4623  global $ilDB;
4624 
4625  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_anonymous WHERE survey_fi = %s AND user_key IS NULL",
4626  array('integer'),
4627  array($this->getSurveyId())
4628  );
4629  return $result->numRows();
4630  }
4631 
4639  function getSurveyCodesForExport($a_array)
4640  {
4641  global $ilDB, $ilUser;
4642 
4643  $result = $ilDB->queryF("SELECT svy_anonymous.*, svy_finished.state FROM svy_anonymous ".
4644  "LEFT JOIN svy_finished ON svy_anonymous.survey_key = svy_finished.anonymous_id ".
4645  "WHERE svy_anonymous.survey_fi = %s AND svy_anonymous.user_key IS NULL",
4646  array('integer'),
4647  array($this->getSurveyId())
4648  );
4649  $export = "";
4650  $default_lang = $ilUser->getPref("survey_code_language");
4651  $lang = (strlen($default_lang)) ? "&lang=" . $default_lang : "";
4652  while ($row = $ilDB->fetchAssoc($result))
4653  {
4654  if (in_array($row["survey_key"], $a_array) || (count($a_array) == 0))
4655  {
4656  $export .= $row["survey_key"] . ",";
4657 
4658  // No relative (today, tomorrow...) dates in export.
4659  $date = new ilDate($row['tstamp'],IL_CAL_UNIX);
4660  $created = $date->get(IL_CAL_DATE);
4661  $export .= "$created,";
4662  if ($this->isSurveyCodeUsed($row["survey_key"]))
4663  {
4664  $export .= "1,";
4665  }
4666  else
4667  {
4668  $export .= "0,";
4669  }
4670  $url = ILIAS_HTTP_PATH."/goto.php?cmd=infoScreen&target=svy_".$this->getRefId() . "&client_id=" . CLIENT_ID . "&accesscode=".$row["survey_key"].$lang;
4671  $export .= $url . "\n";
4672  }
4673  }
4674  return $export;
4675  }
4676 
4684  public function &getSurveyCodesTableData($lang = "en")
4685  {
4686  global $ilDB;
4687 
4688  include_once "./classes/class.ilFormat.php";
4689  if (strlen($lang) == 0) $lang = "en";
4690 
4691  $order = "ORDER BY tstamp, survey_key ASC";
4692  $codes = array();
4693  $result = $ilDB->queryF("SELECT svy_anonymous.anonymous_id, svy_anonymous.survey_key, svy_anonymous.survey_fi, ".
4694  "svy_anonymous.tstamp, svy_finished.state FROM svy_anonymous LEFT JOIN svy_finished ".
4695  "ON svy_anonymous.survey_key = svy_finished.anonymous_id WHERE svy_anonymous.survey_fi = %s ".
4696  "AND svy_anonymous.user_key IS NULL $order",
4697  array('integer'),
4698  array($this->getSurveyId())
4699  );
4700  if ($result->numRows() > 0)
4701  {
4702  while ($row = $ilDB->fetchAssoc($result))
4703  {
4704  $created = ilDatePresentation::formatDate(new ilDateTime($row["tstamp"],IL_CAL_UNIX));
4705  $url = "";
4706 
4707  $state = 0;
4708  if ($this->isSurveyCodeUsed($row["survey_key"]))
4709  {
4710  $state = 1;
4711  }
4712  else
4713  {
4714  $addlang = "";
4715  if (strlen($lang))
4716  {
4717  $addlang = "&amp;lang=$lang";
4718  }
4719  $href = ILIAS_HTTP_PATH."/goto.php?cmd=infoScreen&target=svy_".$this->getRefId() . "&amp;client_id=" . CLIENT_ID . "&amp;accesscode=".$row["survey_key"].$addlang;
4720  $url = $this->lng->txt("survey_code_url_name");
4721  }
4722  array_push($codes, array('code' => $row["survey_key"], 'date' => $created, 'used' => $state, 'url' => $url, 'href' => $href));
4723  }
4724  }
4725  return $codes;
4726  }
4727 
4728  function isSurveyCodeUsed($code)
4729  {
4730  global $ilDB;
4731  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s AND anonymous_id = %s",
4732  array('integer','text'),
4733  array($this->getSurveyId(), $code)
4734  );
4735  return ($result->numRows() > 0) ? true : false;
4736  }
4737 
4738  function isSurveyCodeUnique($code)
4739  {
4740  global $ilDB;
4741  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_anonymous WHERE survey_fi = %s AND survey_key = %s",
4742  array('integer','text'),
4743  array($this->getSurveyId(), $code)
4744  );
4745  return ($result->numRows() > 0) ? false : true;
4746  }
4747 
4748  function createSurveyCodes($nrOfCodes)
4749  {
4750  global $ilDB;
4751  for ($i = 0; $i < $nrOfCodes; $i++)
4752  {
4753  $anonymize_key = $this->createNewAccessCode();
4754  $next_id = $ilDB->nextId('svy_anonymous');
4755  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, tstamp) ".
4756  "VALUES (%s, %s, %s, %s)",
4757  array('integer','text','integer','integer'),
4758  array($next_id, $anonymize_key, $this->getSurveyId(), time())
4759  );
4760  }
4761  }
4762 
4764  {
4765  global $ilDB;
4766  foreach ($data as $dataset)
4767  {
4768  $anonymize_key = $this->createNewAccessCode();
4769  $next_id = $ilDB->nextId('svy_anonymous');
4770  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, externaldata, tstamp) ".
4771  "VALUES (%s, %s, %s, %s, %s)",
4772  array('integer','text','integer','text','integer'),
4773  array($next_id, $anonymize_key, $this->getSurveyId(), serialize($dataset), time())
4774  );
4775  }
4776  }
4777 
4778  function sendCodes($not_sent, $subject, $message, $lang = "en")
4779  {
4780  /*
4781  * 0 = all
4782  * 1 = not sent
4783  * 2 = finished
4784  * 3 = not finished
4785  */
4786  $check_finished = ($not_sent > 1);
4787 
4788  include_once "./Services/Mail/classes/class.ilMail.php";
4789  $user_id = $this->getOwner();
4790  $mail = new ilMail($user_id);
4791  $recipients = $this->getExternalCodeRecipients($check_finished);
4792  foreach ($recipients as $data)
4793  {
4794  if($data['email'] && $data['code'])
4795  {
4796  $do_send = false;
4797  switch ((int)$not_sent)
4798  {
4799  case 1:
4800  $do_send = !(bool)$data['sent'];
4801  break;
4802 
4803  case 2:
4804  $do_send = $data['finished'];
4805  break;
4806 
4807  case 3:
4808  $do_send = !$data['finished'];
4809  break;
4810 
4811  default:
4812  $do_send = true;
4813  break;
4814  }
4815  if ($do_send)
4816  {
4817  // build text
4818  $messagetext = $message;
4819  $url = ILIAS_HTTP_PATH."/goto.php?cmd=infoScreen&target=svy_".$this->getRefId() . "&client_id=" . CLIENT_ID . "&accesscode=".$data["code"]."&lang=".$lang;
4820  $messagetext = str_replace('[url]', "<" . $url . ">", $messagetext);
4821  foreach ($data as $key => $value)
4822  {
4823  $messagetext = str_replace('[' . $key . ']', $value, $messagetext);
4824  }
4825 
4826  // send mail
4827  $mail->sendMail(
4828  $data['email'], // to
4829  "", // cc
4830  "", // bcc
4831  $subject, // subject
4832  $messagetext, // message
4833  array(), // attachments
4834  array('normal') // type
4835  );
4836  }
4837  }
4838  }
4839 
4840  global $ilDB;
4841  $affectedRows = $ilDB->manipulateF("UPDATE svy_anonymous SET sent = %s WHERE survey_fi = %s AND externaldata IS NOT NULL",
4842  array('integer','integer'),
4843  array(1, $this->getSurveyId())
4844  );
4845  }
4846 
4847  function getExternalCodeRecipients($a_check_finished = false)
4848  {
4849  global $ilDB;
4850  $result = $ilDB->queryF("SELECT survey_key code, externaldata, sent FROM svy_anonymous WHERE survey_fi = %s AND externaldata IS NOT NULL",
4851  array('integer'),
4852  array($this->getSurveyId())
4853  );
4854  $res = array();
4855  while ($row = $ilDB->fetchAssoc($result))
4856  {
4857  $externaldata = unserialize($row['externaldata']);
4858  $externaldata['code'] = $row['code'];
4859  $externaldata['sent'] = $row['sent'];
4860 
4861  if($a_check_finished)
4862  {
4863  $externaldata['finished'] = $this->isSurveyCodeUsed($row['code']);
4864  }
4865 
4866  array_push($res, $externaldata);
4867  }
4868  return $res;
4869  }
4870 
4876  function deleteSurveyCode($survey_code)
4877  {
4878  global $ilDB;
4879 
4880  if (strlen($survey_code) > 0)
4881  {
4882  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_anonymous WHERE survey_fi = %s AND survey_key = %s",
4883  array('integer', 'text'),
4884  array($this->getSurveyId(), $survey_code)
4885  );
4886  }
4887  }
4888 
4895  function getUserAccessCode($user_id)
4896  {
4897  global $ilDB;
4898  $access_code = "";
4899  $result = $ilDB->queryF("SELECT survey_key FROM svy_anonymous WHERE survey_fi = %s AND user_key = %s",
4900  array('integer','text'),
4901  array($this->getSurveyId(), md5($user_id))
4902  );
4903  if ($result->numRows())
4904  {
4905  $row = $ilDB->fetchAssoc($result);
4906  $access_code = $row["survey_key"];
4907  }
4908  return $access_code;
4909  }
4910 
4917  function saveUserAccessCode($user_id, $access_code)
4918  {
4919  global $ilDB;
4920  $next_id = $ilDB->nextId('svy_anonymous');
4921  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, user_key, tstamp) ".
4922  "VALUES (%s, %s, %s, %s, %s)",
4923  array('integer','text', 'integer', 'text', 'integer'),
4924  array($next_id, $access_code, $this->getSurveyId(), md5($user_id), time())
4925  );
4926  }
4927 
4934  {
4935  // create a 5 character code
4936  $codestring = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
4937  mt_srand();
4938  $code = "";
4939  for ($i = 1; $i <=5; $i++)
4940  {
4941  $index = mt_rand(0, strlen($codestring)-1);
4942  $code .= substr($codestring, $index, 1);
4943  }
4944  // verify it against the database
4945  while (!$this->isSurveyCodeUnique($code))
4946  {
4947  $code = $this->createNewAccessCode();
4948  }
4949  return $code;
4950  }
4951 
4952 
4963  function &processCSVRow($row, $quoteAll = FALSE, $separator = ";")
4964  {
4965  $resultarray = array();
4966  foreach ($row as $rowindex => $entry)
4967  {
4968  if(is_array($entry))
4969  {
4970  $entry = implode("/", $entry);
4971  }
4972  $surround = FALSE;
4973  if ($quoteAll)
4974  {
4975  $surround = TRUE;
4976  }
4977  if (strpos($entry, "\"") !== FALSE)
4978  {
4979  $entry = str_replace("\"", "\"\"", $entry);
4980  $surround = TRUE;
4981  }
4982  if (strpos($entry, $separator) !== FALSE)
4983  {
4984  $surround = TRUE;
4985  }
4986  // replace all CR LF with LF (for Excel for Windows compatibility
4987  $entry = str_replace(chr(13).chr(10), chr(10), $entry);
4988  if ($surround)
4989  {
4990  $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
4991  }
4992  else
4993  {
4994  $resultarray[$rowindex] = utf8_decode($entry);
4995  }
4996  }
4997  return $resultarray;
4998  }
4999 
5000  function _getLastAccess($finished_id)
5001  {
5002  global $ilDB;
5003 
5004  $result = $ilDB->queryF("SELECT tstamp FROM svy_answer WHERE active_fi = %s ORDER BY tstamp DESC",
5005  array('integer'),
5006  array($finished_id)
5007  );
5008  if ($result->numRows())
5009  {
5010  $row = $ilDB->fetchAssoc($result);
5011  return $row["tstamp"];
5012  }
5013  else
5014  {
5015  $result = $ilDB->queryF("SELECT tstamp FROM svy_finished WHERE finished_id = %s",
5016  array('integer'),
5017  array($finished_id)
5018  );
5019  if ($result->numRows())
5020  {
5021  $row = $ilDB->fetchAssoc($result);
5022  return $row["tstamp"];
5023  }
5024  }
5025  return "";
5026  }
5027 
5034  function prepareTextareaOutput($txt_output)
5035  {
5036  include_once "./Services/Utilities/classes/class.ilUtil.php";
5037  return ilUtil::prepareTextareaOutput($txt_output, $prepare_for_latex_output);
5038  }
5039 
5047  function isHTML($a_text)
5048  {
5049  if (preg_match("/<[^>]*?>/", $a_text))
5050  {
5051  return TRUE;
5052  }
5053  else
5054  {
5055  return FALSE;
5056  }
5057  }
5058 
5067  function addMaterialTag(&$a_xml_writer, $a_material, $close_material_tag = TRUE, $add_mobs = TRUE, $attribs = NULL)
5068  {
5069  include_once "./Services/RTE/classes/class.ilRTE.php";
5070  include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php");
5071 
5072  $a_xml_writer->xmlStartTag("material", $attribs);
5073  $attrs = array(
5074  "type" => "text/plain"
5075  );
5076  if ($this->isHTML($a_material))
5077  {
5078  $attrs["type"] = "text/xhtml";
5079  }
5080  $mattext = ilRTE::_replaceMediaObjectImageSrc($a_material, 0);
5081  $a_xml_writer->xmlElement("mattext", $attrs, $mattext);
5082 
5083  if ($add_mobs)
5084  {
5085  $mobs = ilObjMediaObject::_getMobsOfObject("svy:html", $this->getId());
5086  foreach ($mobs as $mob)
5087  {
5088  $mob_id = "il_" . IL_INST_ID . "_mob_" . $mob;
5089  if (strpos($mattext, $mob_id) !== FALSE)
5090  {
5091  $mob_obj =& new ilObjMediaObject($mob);
5092  $imgattrs = array(
5093  "label" => $mob_id,
5094  "uri" => "objects/" . "il_" . IL_INST_ID . "_mob_" . $mob . "/" . $mob_obj->getTitle()
5095  );
5096  $a_xml_writer->xmlElement("matimage", $imgattrs, NULL);
5097  }
5098  }
5099  }
5100  if ($close_material_tag) $a_xml_writer->xmlEndTag("material");
5101  }
5102 
5112  {
5113  if ($this->getAnonymize() != ANONYMIZE_OFF)
5114  {
5115  if ($this->surveyCodeSecurity == FALSE)
5116  {
5117  return TRUE;
5118  }
5119  }
5120  return FALSE;
5121  }
5122 
5130  function processPrintoutput2FO($print_output)
5131  {
5132  $print_output = str_replace("&nbsp;", "&#160;", $print_output);
5133  $print_output = str_replace("&otimes;", "X", $print_output);
5134  $xsl = file_get_contents("./Modules/Survey/xml/question2fo.xsl");
5135  $args = array( '/_xml' => $print_output, '/_xsl' => $xsl );
5136  $xh = xslt_create();
5137  $params = array();
5138  $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", NULL, $args, $params);
5139  xslt_error($xh);
5140  xslt_free($xh);
5141  global $ilLog; $ilLog->write($output);
5142  return $output;
5143  }
5144 
5151  function deliverPDFfromFO($fo)
5152  {
5153  global $ilLog;
5154 
5155  include_once "./Services/Utilities/classes/class.ilUtil.php";
5156  $fo_file = ilUtil::ilTempnam() . ".fo";
5157  $fp = fopen($fo_file, "w"); fwrite($fp, $fo); fclose($fp);
5158 
5159  include_once './Services/WebServices/RPC/classes/class.ilRpcClientFactory.php';
5160  try
5161  {
5162  $pdf_base64 = ilRpcClientFactory::factory('RPCTransformationHandler')->ilFO2PDF($fo);
5163  ilUtil::deliverData($pdf_base64->scalar, ilUtil::getASCIIFilename($this->getTitle()) . ".pdf", "application/pdf");
5164  return true;
5165  }
5166  catch(XML_RPC2_FaultException $e)
5167  {
5168  $ilLog->write(__METHOD__.': '.$e->getMessage());
5169  return false;
5170  }
5171  catch(Exception $e)
5172  {
5173  $ilLog->write(__METHOD__.': '.$e->getMessage());
5174  return false;
5175  }
5176 
5177  /*
5178  include_once "./Services/Transformation/classes/class.ilFO2PDF.php";
5179  $fo2pdf = new ilFO2PDF();
5180  $fo2pdf->setFOString($fo);
5181  $result = $fo2pdf->send();
5182  ilUtil::deliverData($result, ilUtil::getASCIIFilename($this->getTitle()) . ".pdf", "application/pdf");
5183  */
5184  }
5185 
5186  function _checkCondition($a_svy_id,$a_operator,$a_value,$a_usr_id = 0)
5187  {
5188  global $ilUser;
5189 
5190  $a_usr_id = $a_usr_id ? $a_usr_id : $ilUser->getId();
5191 
5192  switch($a_operator)
5193  {
5194  case 'finished':
5195  //if (ilExerciseMembers::_lookupStatus($a_exc_id, $ilias->account->getId()) == "passed")
5196  include_once("./Modules/Survey/classes/class.ilObjSurveyAccess.php");
5197  if (ilObjSurveyAccess::_lookupFinished($a_svy_id, $a_usr_id))
5198  {
5199  return true;
5200  }
5201  else
5202  {
5203  return false;
5204  }
5205  break;
5206 
5207  default:
5208  return true;
5209  }
5210  return true;
5211  }
5212 
5219  function isPluginActive($a_pname)
5220  {
5221  global $ilPluginAdmin;
5222  if ($ilPluginAdmin->isActive(IL_COMP_MODULE, "SurveyQuestionPool", "svyq", $a_pname))
5223  {
5224  return TRUE;
5225  }
5226  else
5227  {
5228  return FALSE;
5229  }
5230  }
5231 
5237  public function setSurveyId($survey_id)
5238  {
5239  $this->survey_id = $survey_id;
5240  }
5241 
5248  public function &getUserData($ids)
5249  {
5250  global $ilDB;
5251 
5252  if (!is_array($ids) || count($ids) ==0) return array();
5253 
5254  $result = $ilDB->query("SELECT usr_id, login, lastname, firstname FROM usr_data WHERE " . $ilDB->in('usr_id', $ids, false, 'integer') . " ORDER BY login");
5255  $result_array = array();
5256  while ($row = $ilDB->fetchAssoc($result))
5257  {
5258  $result_array[$row["usr_id"]]= $row;
5259  }
5260  return $result_array;
5261  }
5262 
5263  function &getGroupData($ids)
5264  {
5265  if (!is_array($ids) || count($ids) ==0) return array();
5266  $result = array();
5267  foreach ($ids as $ref_id)
5268  {
5269  $obj_id = ilObject::_lookupObjId($ref_id);
5270  $result[$ref_id] = array("ref_id" => $ref_id, "title" => ilObject::_lookupTitle($obj_id), "description" => ilObject::_lookupDescription($obj_id));
5271  }
5272  return $result;
5273  }
5274 
5275  function &getRoleData($ids)
5276  {
5277  if (!is_array($ids) || count($ids) ==0) return array();
5278  $result = array();
5279  foreach ($ids as $obj_id)
5280  {
5281  $result[$obj_id] = array("obj_id" => $obj_id, "title" => ilObject::_lookupTitle($obj_id), "description" => ilObject::_lookupDescription($obj_id));
5282  }
5283  return $result;
5284  }
5285 
5287  {
5288  return $this->mailnotification;
5289  }
5290 
5291  function setMailNotification($a_notification)
5292  {
5293  $this->mailnotification = ($a_notification) ? true : false;
5294  }
5295 
5296  function getMailAddresses()
5297  {
5298  return $this->mailaddresses;
5299  }
5300 
5301  function setMailAddresses($a_addresses)
5302  {
5303  $this->mailaddresses = $a_addresses;
5304  }
5305 
5307  {
5309  }
5310 
5311  function setMailParticipantData($a_data)
5312  {
5313  $this->mailparticipantdata = $a_data;
5314  }
5315 
5316  public function getSurveyTimes()
5317  {
5318  global $ilDB;
5319 
5320  $result = $ilDB->queryF("SELECT * FROM svy_times, svy_finished WHERE svy_finished.survey_fi = %s",
5321  array('integer'),
5322  array($this->getId())
5323  );
5324  $times = array();;
5325  while ($row = $ilDB->fetchAssoc($result))
5326  {
5327  if (strlen($row['left_page']) && strlen($row['entered_page']))
5328  $times[$row['finished_fi']] += ($row['left_page']-$row['entered_page']);
5329  }
5330  return $times;
5331  }
5332 
5333  function setStartTime($finished_id, $first_question)
5334  {
5335  global $ilDB;
5336  $time = time();
5337  $_SESSION['svy_entered_page'] = $time;
5338  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_times (finished_fi, entered_page, left_page, first_question) VALUES (%s, %s, %s, %s)",
5339  array('integer', 'integer', 'integer', 'integer'),
5340  array($finished_id, $time, NULL, $first_question)
5341  );
5342  }
5343 
5344  function setEndTime($finished_id)
5345  {
5346  global $ilDB;
5347  $time = time();
5348  $affectedRows = $ilDB->manipulateF("UPDATE svy_times SET left_page = %s WHERE finished_fi = %s AND entered_page = %s",
5349  array('integer', 'integer', 'integer'),
5350  array($time, $finished_id, $_SESSION['svy_entered_page'])
5351  );
5352  unset($_SESSION['svy_entered_page']);
5353  }
5354 
5355  function getWorkingtimeForParticipant($finished_id)
5356  {
5357  global $ilDB;
5358 
5359  $result = $ilDB->queryF("SELECT * FROM svy_times WHERE finished_fi = %s",
5360  array('integer'),
5361  array($finished_id)
5362  );
5363  $total = 0;
5364  while ($row = $ilDB->fetchAssoc($result))
5365  {
5366  if ($row['left_page'] > 0 && $row['entered_page'] > 0)
5367  $total += $row['left_page'] - $row['entered_page'];
5368  }
5369  return $total;
5370  }
5371 
5373  {
5374  $this->template_id = (int)$template_id;
5375  }
5376 
5377  function getTemplate()
5378  {
5379  return $this->template_id;
5380  }
5381 
5382  function updateOrder(array $a_order)
5383  {
5384  if(sizeof($this->questions) == sizeof($a_order))
5385  {
5386  $this->questions = array_flip($a_order);
5387  $this->saveQuestionsToDB();
5388  }
5389  }
5390 
5391  function getPoolUsage()
5392  {
5393  return $this->pool_usage;
5394  }
5395 
5396  function setPoolUsage($a_value)
5397  {
5398  $this->pool_usage = (bool)$a_value;
5399  }
5400 
5406  function isPoolActive()
5407  {
5408  $use_pool = (bool)$this->getPoolUsage();
5409  $template_settings = $this->getTemplate();
5410  if($template_settings)
5411  {
5412  include_once "Services/Administration/classes/class.ilSettingsTemplate.php";
5413  $template_settings = new ilSettingsTemplate($template_settings);
5414  $template_settings = $template_settings->getSettings();
5415  $template_settings = $template_settings["use_pool"];
5416  if($template_settings && $template_settings["hide"])
5417  {
5418  $use_pool = (bool)$template_settings["value"];
5419  }
5420  }
5421  return $use_pool;
5422  }
5423 
5430  {
5431  if(!$template_id)
5432  {
5433  return;
5434  }
5435 
5436  include_once "Services/Administration/classes/class.ilSettingsTemplate.php";
5437  $template = new ilSettingsTemplate($template_id);
5438  $template_settings = $template->getSettings();
5439  if($template_settings)
5440  {
5441  if($template_settings["show_question_titles"] !== NULL)
5442  {
5443  if($template_settings["show_question_titles"]["value"])
5444  {
5445  $this->setShowQuestionTitles(true);
5446  }
5447  else
5448  {
5449  $this->setShowQuestionTitles(false);
5450  }
5451  }
5452 
5453  if($template_settings["use_pool"] !== NULL)
5454  {
5455  if($template_settings["use_pool"]["value"])
5456  {
5457  $this->setPoolUsage(true);
5458  }
5459  else
5460  {
5461  $this->setPoolUsage(false);
5462  }
5463  }
5464 
5465  if($template_settings["anonymization_options"]["value"])
5466  {
5467  $anon_map = array('personalized' => ANONYMIZE_OFF,
5468  'anonymize_with_code' => ANONYMIZE_ON,
5469  'anonymize_without_code' => ANONYMIZE_FREEACCESS);
5470  $this->setAnonymize($anon_map[$template_settings["anonymization_options"]["value"]]);
5471  }
5472 
5473  /* other settings: not needed here
5474  * - enabled_end_date
5475  * - enabled_start_date
5476  * - rte_switch
5477  */
5478  }
5479 
5480  $this->setTemplate($template_id);
5481  $this->saveToDb();
5482  }
5483 
5484 } // END class.ilObjSurvey
5485 
5486 ?>