ILIAS  Release_4_1_x_branch Revision 61804
 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 
154 
161  function ilObjSurvey($a_id = 0,$a_call_by_reference = true)
162  {
163  global $ilUser;
164  $this->type = "svy";
165  $this->ilObject($a_id,$a_call_by_reference);
166 
167  $this->survey_id = -1;
168  $this->introduction = "";
169  $this->outro = $this->lng->txt("survey_finished");
170  $this->author = $ilUser->fullname;
171  $this->status = STATUS_OFFLINE;
172  $this->evaluation_access = EVALUATION_ACCESS_OFF;
173  $this->startdate_enabled = 0;
174  $this->enddate_enabled = 0;
175  $this->questions = array();
176  $this->invitation = INVITATION_OFF;
177  $this->invitation_mode = MODE_PREDEFINED_USERS;
178  $this->anonymize = ANONYMIZE_OFF;
179  $this->display_question_titles = QUESTIONTITLES_VISIBLE;
180  $this->surveyCodeSecurity = TRUE;
181  $this->mailnotification = false;
182  }
183 
187  function create($a_upload = false)
188  {
189  parent::create();
190  if(!$a_upload)
191  {
192  $this->createMetaData();
193  }
194  }
195 
201  function createMetaData()
202  {
204  $this->saveAuthorToMetadata();
205  }
206 
213  function update()
214  {
215  $this->updateMetaData();
216 
217  if (!parent::update())
218  {
219  return false;
220  }
221 
222  // put here object specific stuff
223 
224  return true;
225  }
226 
227  function createReference()
228  {
230  $this->saveToDb();
231  return $result;
232  }
233 
239  function read($a_force_db = false)
240  {
241  parent::read($a_force_db);
242  $this->loadFromDb();
243  }
244 
251  function addQuestion($question_id)
252  {
253  array_push($this->questions, $question_id);
254  }
255 
256 
263  function delete()
264  {
265  $remove = parent::delete();
266  // always call parent delete function first!!
267  if (!$remove)
268  {
269  return false;
270  }
271 
272  $this->deleteMetaData();
273 
274  // Delete all survey questions, constraints and materials
275  foreach ($this->questions as $question_id)
276  {
277  $this->removeQuestion($question_id);
278  }
279  $this->deleteSurveyRecord();
280 
282  return true;
283  }
284 
291  {
292  global $ilDB;
293 
294  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_svy WHERE survey_id = %s",
295  array('integer'),
296  array($this->getSurveyId())
297  );
298 
299  $result = $ilDB->queryF("SELECT questionblock_fi FROM svy_qblk_qst WHERE survey_fi = %s",
300  array('integer'),
301  array($this->getSurveyId())
302  );
303  $questionblocks = array();
304  while ($row = $ilDB->fetchAssoc($result))
305  {
306  array_push($questionblocks, $row["questionblock_fi"]);
307  }
308  if (count($questionblocks))
309  {
310  $affectedRows = $ilDB->manipulate("DELETE FROM svy_qblk WHERE " . $ilDB->in('questionblock_id', $questionblocks, false, 'integer'));
311  }
312  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE survey_fi = %s",
313  array('integer'),
314  array($this->getSurveyId())
315  );
316  $this->deleteAllUserData();
317 
318  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_anonymous WHERE survey_fi = %s",
319  array('integer'),
320  array($this->getSurveyId())
321  );
322 
323  // delete export files
324  include_once "./Services/Utilities/classes/class.ilUtil.php";
325  $svy_data_dir = ilUtil::getDataDir()."/svy_data";
326  $directory = $svy_data_dir."/svy_".$this->getId();
327  if (is_dir($directory))
328  {
329  include_once "./Services/Utilities/classes/class.ilUtil.php";
330  ilUtil::delDir($directory);
331  }
332 
333  include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php");
334  $mobs = ilObjMediaObject::_getMobsOfObject("svy:html", $this->getId());
335  // remaining usages are not in text anymore -> delete them
336  // and media objects (note: delete method of ilObjMediaObject
337  // checks whether object is used in another context; if yes,
338  // the object is not deleted!)
339  foreach($mobs as $mob)
340  {
341  ilObjMediaObject::_removeUsage($mob, "svy:html", $this->getId());
342  $mob_obj =& new ilObjMediaObject($mob);
343  $mob_obj->delete();
344  }
345  }
346 
352  function deleteAllUserData()
353  {
354  global $ilDB;
355 
356  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
357  array('integer'),
358  array($this->getSurveyId())
359  );
360  $active_array = array();
361  while ($row = $ilDB->fetchAssoc($result))
362  {
363  array_push($active_array, $row["finished_id"]);
364  }
365 
366  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_finished WHERE survey_fi = %s",
367  array('integer'),
368  array($this->getSurveyId())
369  );
370 
371  foreach ($active_array as $active_fi)
372  {
373  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE active_fi = %s",
374  array('integer'),
375  array($active_fi)
376  );
377  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_times WHERE finished_fi = %s",
378  array('integer'),
379  array($active_fi)
380  );
381  }
382  }
383 
389  function removeSelectedSurveyResults($finished_ids)
390  {
391  global $ilDB;
392 
393  foreach ($finished_ids as $finished_id)
394  {
395  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE finished_id = %s",
396  array('integer'),
397  array($finished_id)
398  );
399  $row = $ilDB->fetchAssoc($result);
400 
401  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE active_fi = %s",
402  array('integer'),
403  array($row["finished_id"])
404  );
405 
406  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_finished WHERE finished_id = %s",
407  array('integer'),
408  array($finished_id)
409  );
410 
411  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_times WHERE finished_fi = %s",
412  array('integer'),
413  array($row["finished_id"])
414  );
415  }
416  }
417 
419  {
420  global $ilDB;
421 
422  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s",
423  array('integer'),
424  array($this->getSurveyId())
425  );
426  $participants = array();
427  if ($result->numRows() > 0)
428  {
429  while ($row = $ilDB->fetchAssoc($result))
430  {
431  $userdata = $this->getUserDataFromActiveId($row["finished_id"]);
432  $participants[$userdata["sortname"] . $userdata["active_id"]] = $userdata;
433  }
434  }
435  return $participants;
436  }
437 
451  function notify($a_event,$a_ref_id,$a_parent_non_rbac_id,$a_node_id,$a_params = 0)
452  {
453  global $tree;
454 
455  switch ($a_event)
456  {
457  case "link":
458 
459  //var_dump("<pre>",$a_params,"</pre>");
460  //echo "Module name ".$this->getRefId()." triggered by link event. Objects linked into target object ref_id: ".$a_ref_id;
461  //exit;
462  break;
463 
464  case "cut":
465 
466  //echo "Module name ".$this->getRefId()." triggered by cut event. Objects are removed from target object ref_id: ".$a_ref_id;
467  //exit;
468  break;
469 
470  case "copy":
471 
472  //var_dump("<pre>",$a_params,"</pre>");
473  //echo "Module name ".$this->getRefId()." triggered by copy event. Objects are copied into target object ref_id: ".$a_ref_id;
474  //exit;
475  break;
476 
477  case "paste":
478 
479  //echo "Module name ".$this->getRefId()." triggered by paste (cut) event. Objects are pasted into target object ref_id: ".$a_ref_id;
480  //exit;
481  break;
482 
483  case "new":
484 
485  //echo "Module name ".$this->getRefId()." triggered by paste (new) event. Objects are applied to target object ref_id: ".$a_ref_id;
486  //exit;
487  break;
488  }
489 
490  // At the beginning of the recursive process it avoids second call of the notify function with the same parameter
491  if ($a_node_id==$_GET["ref_id"])
492  {
493  $parent_obj =& $this->ilias->obj_factory->getInstanceByRefId($a_node_id);
494  $parent_type = $parent_obj->getType();
495  if($parent_type == $this->getType())
496  {
497  $a_node_id = (int) $tree->getParentId($a_node_id);
498  }
499  }
500 
501  parent::notify($a_event,$a_ref_id,$a_parent_non_rbac_id,$a_node_id,$a_params);
502  }
503 
510  function isComplete()
511  {
512  if (($this->getTitle()) and (count($this->questions)))
513  {
514  return 1;
515  }
516  else
517  {
518  return 0;
519  }
520  }
521 
528  function _isComplete($obj_id)
529  {
530  $survey = new ilObjSurvey($obj_id, false);
531  $survey->loadFromDb();
532  if (($survey->getTitle()) and (count($survey->questions)))
533  {
534  return 1;
535  }
536  else
537  {
538  return 0;
539  }
540  }
541 
548  function &_getGlobalSurveyData($obj_id)
549  {
550  $survey = new ilObjSurvey($obj_id, false);
551  $survey->loadFromDb();
552  $result = array();
553  if (($survey->getTitle()) and ($survey->author) and (count($survey->questions)))
554  {
555  $result["complete"] = true;
556  }
557  else
558  {
559  $result["complete"] = false;
560  }
561  $result["evaluation_access"] = $survey->getEvaluationAccess();
562  return $result;
563  }
564 
571  {
572  global $ilDB;
573 
574  $complete = 0;
575  if ($this->isComplete())
576  {
577  $complete = 1;
578  }
579  if ($this->getSurveyId() > 0)
580  {
581  $affectedRows = $ilDB->manipulateF("UPDATE svy_svy SET complete = %s, tstamp = %s WHERE survey_id = %s",
582  array('text','integer','integer'),
583  array($this->isComplete(), time(), $this->getSurveyId())
584  );
585  }
586  }
587 
595  function duplicateQuestionForSurvey($question_id)
596  {
597  global $ilUser;
598 
599  $questiontype = $this->getQuestionType($question_id);
600  $question_gui = $this->getQuestionGUI($questiontype, $question_id);
601  $duplicate_id = $question_gui->object->duplicate(true);
602  return $duplicate_id;
603  }
604 
610  function insertQuestion($question_id)
611  {
612  global $ilDB;
613 
614  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
615  if (!SurveyQuestion::_isComplete($question_id))
616  {
617  return FALSE;
618  }
619  else
620  {
621  // get maximum sequence index in test
622  $result = $ilDB->queryF("SELECT survey_question_id FROM svy_svy_qst WHERE survey_fi = %s",
623  array('integer'),
624  array($this->getSurveyId())
625  );
626  $sequence = $result->numRows();
627  $duplicate_id = $this->duplicateQuestionForSurvey($question_id);
628  $next_id = $ilDB->nextId('svy_svy_qst');
629  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_svy_qst (survey_question_id, survey_fi, question_fi, sequence, tstamp) VALUES (%s, %s, %s, %s, %s)",
630  array('integer', 'integer', 'integer', 'integer', 'integer'),
631  array($next_id, $this->getSurveyId(), $duplicate_id, $sequence, time())
632  );
633  $this->loadQuestionsFromDb();
634  return TRUE;
635  }
636  }
637 
638 
644  function insertQuestionblock($questionblock_id)
645  {
646  global $ilDB;
647  $result = $ilDB->queryF("SELECT svy_qblk.title, svy_qblk.show_questiontext, svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst, svy_svy_qst WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_svy_qst.question_fi = svy_qblk_qst.question_fi AND svy_qblk.questionblock_id = %s ORDER BY svy_svy_qst.sequence",
648  array('integer'),
649  array($questionblock_id)
650  );
651  $questions = array();
652  $show_questiontext = 0;
653  while ($row = $ilDB->fetchAssoc($result))
654  {
655  $duplicate_id = $this->duplicateQuestionForSurvey($row["question_fi"]);
656  array_push($questions, $duplicate_id);
657  $title = $row["title"];
658  $show_questiontext = $row["show_questiontext"];
659  }
660  $this->createQuestionblock($title, $show_questiontext, $questions);
661  }
662 
668  function getAllRTEContent()
669  {
670  $result = array();
671  array_push($result, $this->getIntroduction());
672  array_push($result, $this->getOutro());
673  return $result;
674  }
675 
682  {
683  include_once("./Services/RTE/classes/class.ilRTE.php");
684  $completecontent = "";
685  foreach ($this->getAllRTEContent() as $content)
686  {
687  $completecontent .= $content;
688  }
689  ilRTE::_cleanupMediaObjectUsage($completecontent, $this->getType() . ":html",
690  $this->getId());
691  }
692 
693  public function saveUserSettings($usr_id, $key, $title, $value)
694  {
695  global $ilDB;
696 
697  $next_id = $ilDB->nextId('svy_settings');
698  $affectedRows = $ilDB->insert("svy_settings", array(
699  "settings_id" => array("integer", $next_id),
700  "usr_id" => array("integer", $usr_id),
701  "keyword" => array("text", $key),
702  "title" => array("text", $title),
703  "value" => array("clob", $value)
704  ));
705  }
706 
707  public function deleteUserSettings($id)
708  {
709  global $ilDB;
710 
711  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_settings WHERE settings_id = %s",
712  array('integer'),
713  array($id)
714  );
715  return $affectedRows;
716  }
717 
718  public function getUserSettings($usr_id, $key)
719  {
720  global $ilDB;
721 
722  $result = $ilDB->queryF("SELECT * FROM svy_settings WHERE usr_id = %s AND keyword = %s",
723  array('integer', 'text'),
724  array($usr_id, $key)
725  );
726  $found = array();
727  if ($result->numRows())
728  {
729  while ($row = $ilDB->fetchAssoc($result))
730  {
731  $found[$row['settings_id']] = $row;
732  }
733  }
734  return $found;
735  }
736 
742  function saveToDb()
743  {
744  global $ilDB;
745 
746  include_once("./Services/RTE/classes/class.ilRTE.php");
747  if ($this->getSurveyId() < 1)
748  {
749  $next_id = $ilDB->nextId('svy_svy');
750  $affectedRows = $ilDB->insert("svy_svy", array(
751  "survey_id" => array("integer", $next_id),
752  "obj_fi" => array("integer", $this->getId()),
753  "author" => array("text", $this->getAuthor()),
754  "introduction" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getIntroduction(), 0)),
755  "outro" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getOutro(), 0)),
756  "status" => array("text", $this->getStatus()),
757  "startdate" => array("text", $this->getStartDate()),
758  "enddate" => array("text", $this->getEndDate()),
759  "evaluation_access" => array("text", $this->getEvaluationAccess()),
760  "invitation" => array("text", $this->getInvitation()),
761  "invitation_mode" => array("text", $this->getInvitationMode()),
762  "complete" => array("text", $this->isComplete()),
763  "created" => array("integer", time()),
764  "anonymize" => array("text", $this->getAnonymize()),
765  "show_question_titles" => array("text", $this->getShowQuestionTitles()),
766  "mailnotification" => array('integer', ($this->getMailNotification()) ? 1 : 0),
767  "mailaddresses" => array('text', strlen($this->getMailAddresses()) ? $this->getMailAddresses() : NULL),
768  "mailparticipantdata" => array('text', strlen($this->getMailParticipantData()) ? $this->getMailParticipantData() : NULL),
769  "tstamp" => array("integer", time())
770  ));
771  $this->setSurveyId($next_id);
772  }
773  else
774  {
775  $affectedRows = $ilDB->update("svy_svy", array(
776  "author" => array("text", $this->getAuthor()),
777  "introduction" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getIntroduction(), 0)),
778  "outro" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getOutro(), 0)),
779  "status" => array("text", $this->getStatus()),
780  "startdate" => array("text", $this->getStartDate()),
781  "enddate" => array("text", $this->getEndDate()),
782  "evaluation_access" => array("text", $this->getEvaluationAccess()),
783  "invitation" => array("text", $this->getInvitation()),
784  "invitation_mode" => array("text", $this->getInvitationMode()),
785  "complete" => array("text", $this->isComplete()),
786  "anonymize" => array("text", $this->getAnonymize()),
787  "show_question_titles" => array("text", $this->getShowQuestionTitles()),
788  "mailnotification" => array('integer', ($this->getMailNotification()) ? 1 : 0),
789  "mailaddresses" => array('text', strlen($this->getMailAddresses()) ? $this->getMailAddresses() : NULL),
790  "mailparticipantdata" => array('text', strlen($this->getMailParticipantData()) ? $this->getMailParticipantData() : NULL),
791  "tstamp" => array("integer", time())
792  ), array(
793  "survey_id" => array("integer", $this->getSurveyId())
794  ));
795  }
796  if ($affectedRows)
797  {
798  // save questions to db
799  $this->saveQuestionsToDb();
800  }
801  }
802 
809  function saveQuestionsToDb()
810  {
811  global $ilDB;
812  // save old questions state
813  $old_questions = array();
814  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE survey_fi = %s",
815  array('integer'),
816  array($this->getSurveyId())
817  );
818  if ($result->numRows())
819  {
820  while ($row = $ilDB->fetchAssoc($result))
821  {
822  $old_questions[$row["question_fi"]] = $row;
823  }
824  }
825 
826  // delete existing question relations
827  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_svy_qst WHERE survey_fi = %s",
828  array('integer'),
829  array($this->getSurveyId())
830  );
831  // create new question relations
832  foreach ($this->questions as $key => $value)
833  {
834  $next_id = $ilDB->nextId('svy_svy_qst');
835  $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)",
836  array('integer','integer','integer','text','integer','integer'),
837  array($next_id, $this->getSurveyId(), $value, (strlen($old_questions[$value]["heading"])) ? $old_questions[$value]["heading"] : NULL, $key, time())
838  );
839  }
840  }
841 
849  function getAnonymousId($id)
850  {
851  global $ilDB;
852  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_finished WHERE anonymous_id = %s",
853  array('text'),
854  array($id)
855  );
856  if ($result->numRows())
857  {
858  $row = $ilDB->fetchAssoc($result);
859  return $row["anonymous_id"];
860  }
861  else
862  {
863  return "";
864  }
865  }
866 
873  function getQuestionGUI($questiontype, $question_id)
874  {
875  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php";
876  return SurveyQuestionGUI::_getQuestionGUI($questiontype, $question_id);
877  }
878 
886  function getQuestionType($question_id)
887  {
888  global $ilDB;
889  if ($question_id < 1) return -1;
890  $result = $ilDB->queryF("SELECT type_tag FROM svy_question, svy_qtype WHERE svy_question.question_id = %s AND " .
891  "svy_question.questiontype_fi = svy_qtype.questiontype_id",
892  array('integer'),
893  array($question_id)
894  );
895  if ($result->numRows() == 1)
896  {
897  $data = $ilDB->fetchAssoc($result);
898  return $data["type_tag"];
899  }
900  else
901  {
902  return "";
903  }
904  }
905 
912  function getSurveyId()
913  {
914  return $this->survey_id;
915  }
916 
920  function setAnonymize($a_anonymize)
921  {
922  switch ($a_anonymize)
923  {
924  case ANONYMIZE_OFF:
925  case ANONYMIZE_ON:
927  $this->anonymize = $a_anonymize;
928  break;
929  default:
930  $this->anonymize = ANONYMIZE_OFF;
931  break;
932  }
933  }
934 
940  function getAnonymize()
941  {
942  return ($this->anonymize) ? $this->anonymize : 0;
943  }
944 
951  {
952  if ($this->getAnonymize() == ANONYMIZE_FREEACCESS)
953  {
954  return true;
955  }
956  else
957  {
958  return false;
959  }
960  }
961 
967  function loadFromDb()
968  {
969  global $ilDB;
970  $result = $ilDB->queryF("SELECT * FROM svy_svy WHERE obj_fi = %s",
971  array('integer'),
972  array($this->getId())
973  );
974  if ($result->numRows() == 1)
975  {
976  $data = $ilDB->fetchAssoc($result);
977  $this->setSurveyId($data["survey_id"]);
978  $this->setAuthor($data["author"]);
979  include_once("./Services/RTE/classes/class.ilRTE.php");
980  $this->setIntroduction(ilRTE::_replaceMediaObjectImageSrc($data["introduction"], 1));
981  if (strcmp($data["outro"], "survey_finished") == 0)
982  {
983  $this->setOutro($this->lng->txt("survey_finished"));
984  }
985  else
986  {
988  }
989  $this->setInvitation($data["invitation"]);
990  $this->setInvitationMode($data["invitation_mode"]);
991  $this->setShowQuestionTitles($data["show_question_titles"]);
992  $this->setStartDate($data["startdate"]);
993  $this->setStartDateEnabled(strlen($data["startdate"]));
994  $this->setEndDate($data["enddate"]);
995  $this->setEndDateEnabled(strlen($data["enddate"]));
996  $this->setAnonymize($data["anonymize"]);
997  $this->setEvaluationAccess($data["evaluation_access"]);
998  $this->loadQuestionsFromDb();
999  $this->setStatus($data["status"]);
1000  $this->setMailNotification($data['mailnotification']);
1001  $this->setMailAddresses($data['mailaddresses']);
1002  $this->setMailParticipantData($data['mailparticipantdata']);
1003  }
1004  }
1005 
1013  {
1014  global $ilDB;
1015  $this->questions = array();
1016  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE survey_fi = %s ORDER BY sequence",
1017  array('integer'),
1018  array($this->getSurveyId())
1019  );
1020  while ($data = $ilDB->fetchAssoc($result))
1021  {
1022  $this->questions[$data["sequence"]] = $data["question_fi"];
1023  }
1024  }
1025 
1033  function setStartDateEnabled($enabled = false)
1034  {
1035  $this->startdate_enabled = ($enabled) ? $enabled : 0;
1036  }
1037 
1046  {
1047  return ($this->startdate_enabled) ? $this->startdate_enabled : 0;
1048  }
1049 
1057  function setEndDateEnabled($enabled = false)
1058  {
1059  $this->enddate_enabled = ($enabled) ? $enabled : 0;
1060  }
1061 
1070  {
1071  return ($this->enddate_enabled) ? $this->enddate_enabled : 0;
1072  }
1073 
1081  function setAuthor($author = "")
1082  {
1083  $this->author = $author;
1084  }
1085 
1095  function saveAuthorToMetadata($a_author = "")
1096  {
1097  $md =& new ilMD($this->getId(), 0, $this->getType());
1098  $md_life =& $md->getLifecycle();
1099  if (!$md_life)
1100  {
1101  if (strlen($a_author) == 0)
1102  {
1103  global $ilUser;
1104  $a_author = $ilUser->getFullname();
1105  }
1106 
1107  $md_life =& $md->addLifecycle();
1108  $md_life->save();
1109  $con =& $md_life->addContribute();
1110  $con->setRole("Author");
1111  $con->save();
1112  $ent =& $con->addEntity();
1113  $ent->setEntity($a_author);
1114  $ent->save();
1115  }
1116  }
1117 
1125  function getAuthor()
1126  {
1127  $author = array();
1128  include_once "./Services/MetaData/classes/class.ilMD.php";
1129  $md =& new ilMD($this->getId(), 0, $this->getType());
1130  $md_life =& $md->getLifecycle();
1131  if ($md_life)
1132  {
1133  $ids =& $md_life->getContributeIds();
1134  foreach ($ids as $id)
1135  {
1136  $md_cont =& $md_life->getContribute($id);
1137  if (strcmp($md_cont->getRole(), "Author") == 0)
1138  {
1139  $entids =& $md_cont->getEntityIds();
1140  foreach ($entids as $entid)
1141  {
1142  $md_ent =& $md_cont->getEntity($entid);
1143  array_push($author, $md_ent->getEntity());
1144  }
1145  }
1146  }
1147  }
1148  return join($author, ",");
1149  }
1150 
1157  public function getShowQuestionTitles()
1158  {
1159  return ($this->display_question_titles) ? 1 : 0;
1160  }
1161 
1168  public function setShowQuestionTitles($a_show)
1169  {
1170  $this->display_question_titles = ($a_show) ? 1 : 0;
1171  }
1172 
1180  {
1181  $this->display_question_titles = 1;
1182  }
1183 
1191  {
1192  $this->display_question_titles = 0;
1193  }
1194 
1203  {
1204  global $ilDB;
1205  global $ilAccess;
1206  $this->invitation = $invitation;
1207  if ($invitation == INVITATION_OFF)
1208  {
1209  $this->disinviteAllUsers();
1210  }
1211  else if ($invitation == INVITATION_ON)
1212  {
1213  if ($this->getInvitationMode() == MODE_UNLIMITED)
1214  {
1215  $result = $ilDB->query("SELECT usr_id FROM usr_data");
1216  while ($row = $ilDB->fetchAssoc($result))
1217  {
1218  if ($ilAccess->checkAccessOfUser($row["usr_id"], "read", "", $this->getRefId(), "svy", $this->getId()))
1219  {
1220  $this->inviteUser($row['usr_id']);
1221  }
1222  }
1223  }
1224  }
1225  }
1226 
1235  {
1236  $this->invitation_mode = $invitation_mode;
1237  }
1238 
1248  {
1249  $this->invitation_mode = $invitation_mode;
1250  $this->setInvitation($invitation);
1251  }
1252 
1259  public function setIntroduction($introduction = "")
1260  {
1261  $this->introduction = $introduction;
1262  }
1263 
1270  public function setOutro($outro = "")
1271  {
1272  $this->outro = $outro;
1273  }
1274 
1282  function getInvitation()
1283  {
1284  return ($this->invitation) ? $this->invitation : INVITATION_OFF;
1285  }
1286 
1294  function getInvitationMode()
1295  {
1296  include_once "./Services/Administration/classes/class.ilSetting.php";
1297  $surveySetting = new ilSetting("survey");
1298  $unlimited_invitation = $surveySetting->get("unlimited_invitation");
1299  if (!$unlimited_invitation && $this->invitation_mode == MODE_UNLIMITED)
1300  {
1301  return MODE_PREDEFINED_USERS;
1302  }
1303  else
1304  {
1305  return ($this->invitation_mode) ? $this->invitation_mode : MODE_UNLIMITED;
1306  }
1307  }
1308 
1316  function getStatus()
1317  {
1318  return ($this->status) ? $this->status : STATUS_OFFLINE;
1319  }
1320 
1328  function isOnline()
1329  {
1330  return ($this->status == STATUS_ONLINE) ? true : false;
1331  }
1332 
1340  function isOffline()
1341  {
1342  return ($this->status == STATUS_OFFLINE) ? true : false;
1343  }
1344 
1354  {
1355  $result = "";
1356  if (($status == STATUS_ONLINE) && (count($this->questions) == 0))
1357  {
1358  $this->status = STATUS_OFFLINE;
1359  $result = $this->lng->txt("cannot_switch_to_online_no_questions");
1360  }
1361  else
1362  {
1363  $this->status = $status;
1364  }
1365  return $result;
1366  }
1367 
1375  function getStartDate()
1376  {
1377  return (strlen($this->start_date)) ? $this->start_date : NULL;
1378  }
1379 
1386  function canStartSurvey($anonymous_id = NULL)
1387  {
1388  global $ilAccess;
1389 
1390  $result = TRUE;
1391  $messages = array();
1392  // check start date
1393  if ($this->getStartDateEnabled())
1394  {
1395  if (preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getStartDate(), $matches))
1396  {
1397  $epoch_time = mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1398  $now = mktime();
1399  if ($now < $epoch_time)
1400  {
1401  array_push($messages,$this->lng->txt('start_date_not_reached').' ('.
1403  $result = FALSE;
1404  }
1405  }
1406  }
1407  // check end date
1408  if ($this->getEndDateEnabled())
1409  {
1410  if (preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getEndDate(), $matches))
1411  {
1412  $epoch_time = mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1413  $now = mktime();
1414  if ($now > $epoch_time)
1415  {
1416  array_push($messages,$this->lng->txt('end_date_reached').' ('.
1418  $result = FALSE;
1419  }
1420  }
1421  }
1422  // check online status
1423  if ($this->getStatus() == STATUS_OFFLINE)
1424  {
1425  array_push($messages, $this->lng->txt("survey_is_offline"));
1426  $result = FALSE;
1427  }
1428  // check rbac permissions
1429  if (!$ilAccess->checkAccess("read", "", $this->ref_id))
1430  {
1431  array_push($messages, $this->lng->txt("cannot_participate_survey"));
1432  $result = FALSE;
1433  }
1434  // 2. check previous access
1435  if (!$result["error"])
1436  {
1437  global $ilUser;
1438  $survey_started = $this->isSurveyStarted($ilUser->getId(), $anonymous_id);
1439  if ($survey_started === 1)
1440  {
1441  array_push($messages, $this->lng->txt("already_completed_survey"));
1442  $result = FALSE;
1443  }
1444  }
1445  return array(
1446  "result" => $result,
1447  "messages" => $messages
1448  );
1449  }
1450 
1458  function setStartDate($start_date = "")
1459  {
1460  $this->start_date = $start_date;
1461  }
1462 
1471  function setStartDateAndTime($start_date = "", $start_time)
1472  {
1473  $y = ''; $m = ''; $d = ''; $h = ''; $i = ''; $s = '';
1474  if (preg_match("/(\d{4})-(\d{2})-(\d{2})/", $start_date, $matches))
1475  {
1476  $y = $matches[1];
1477  $m = $matches[2];
1478  $d = $matches[3];
1479  }
1480  if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $start_time, $matches))
1481  {
1482  $h = $matches[1];
1483  $i = $matches[2];
1484  $s = $matches[3];
1485  }
1486  $this->start_date = sprintf('%04d%02d%02d%02d%02d%02d', $y, $m, $d, $h, $i, $s);
1487  }
1488 
1496  function getStartMonth()
1497  {
1498  $dt = new ilDateTime($this->getStartDate(), IL_CAL_TIMESTAMP);
1499  return $dt->get(IL_CAL_FKT_DATE, 'm');
1500  }
1501 
1509  function getStartDay()
1510  {
1511  $dt = new ilDateTime($this->getStartDate(), IL_CAL_TIMESTAMP);
1512  return $dt->get(IL_CAL_FKT_DATE, 'd');
1513  }
1514 
1522  function getStartYear()
1523  {
1524  $dt = new ilDateTime($this->getStartDate(), IL_CAL_TIMESTAMP);
1525  return $dt->get(IL_CAL_FKT_DATE, 'Y');
1526  }
1527 
1535  function getStartHour()
1536  {
1537  $dt = new ilDateTime($this->getStartDate(), IL_CAL_TIMESTAMP);
1538  return $dt->get(IL_CAL_FKT_DATE, 'H');
1539  }
1540 
1548  function getStartMinute()
1549  {
1550  $dt = new ilDateTime($this->getStartDate(), IL_CAL_TIMESTAMP);
1551  return $dt->get(IL_CAL_FKT_DATE, 'i');
1552  }
1553 
1561  function getEndDate()
1562  {
1563  return (strlen($this->end_date)) ? $this->end_date : NULL;
1564  }
1565 
1573  function setEndDate($end_date = "")
1574  {
1575  $this->end_date = $end_date;
1576  }
1577 
1586  function setEndDateAndTime($end_date = "", $end_time)
1587  {
1588  $y = ''; $m = ''; $d = ''; $h = ''; $i = ''; $s = '';
1589  if (preg_match("/(\d{4})-(\d{2})-(\d{2})/", $end_date, $matches))
1590  {
1591  $y = $matches[1];
1592  $m = $matches[2];
1593  $d = $matches[3];
1594  }
1595  if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $end_time, $matches))
1596  {
1597  $h = $matches[1];
1598  $i = $matches[2];
1599  $s = $matches[3];
1600  }
1601  $this->end_date = sprintf('%04d%02d%02d%02d%02d%02d', $y, $m, $d, $h, $i, $s);
1602  }
1603 
1611  function getEndMonth()
1612  {
1613  $dt = new ilDateTime($this->getEndDate(), IL_CAL_TIMESTAMP);
1614  return $dt->get(IL_CAL_FKT_DATE, 'm');
1615  }
1616 
1624  function getEndDay()
1625  {
1626  $dt = new ilDateTime($this->getEndDate(), IL_CAL_TIMESTAMP);
1627  return $dt->get(IL_CAL_FKT_DATE, 'd');
1628  }
1629 
1637  function getEndYear()
1638  {
1639  $dt = new ilDateTime($this->getEndDate(), IL_CAL_TIMESTAMP);
1640  return $dt->get(IL_CAL_FKT_DATE, 'Y');
1641  }
1642 
1650  function getEndHour()
1651  {
1652  $dt = new ilDateTime($this->getEndDate(), IL_CAL_TIMESTAMP);
1653  return $dt->get(IL_CAL_FKT_DATE, 'H');
1654  }
1655 
1663  function getEndMinute()
1664  {
1665  $dt = new ilDateTime($this->getEndDate(), IL_CAL_TIMESTAMP);
1666  return $dt->get(IL_CAL_FKT_DATE, 'i');
1667  }
1668 
1677  {
1678  return ($this->evaluation_access) ? $this->evaluation_access : EVALUATION_ACCESS_OFF;
1679  }
1680 
1689  {
1690  $this->evaluation_access = ($evaluation_access) ? $evaluation_access : EVALUATION_ACCESS_OFF;
1691  }
1692 
1700  function getIntroduction()
1701  {
1702  return (strlen($this->introduction)) ? $this->introduction : NULL;
1703  }
1704 
1712  function getOutro()
1713  {
1714  return (strlen($this->outro)) ? $this->outro : NULL;
1715  }
1716 
1724  {
1725  global $ilDB;
1726  $existing_questions = array();
1727  $result = $ilDB->queryF("SELECT svy_question.original_id FROM svy_question, svy_svy_qst WHERE " .
1728  "svy_svy_qst.survey_fi = %s AND svy_svy_qst.question_fi = svy_question.question_id",
1729  array('integer'),
1730  array($this->getSurveyId())
1731  );
1732  while ($data = $ilDB->fetchAssoc($result))
1733  {
1734  array_push($existing_questions, $data["original_id"]);
1735  }
1736  return $existing_questions;
1737  }
1738 
1745  function &getQuestionpoolTitles($could_be_offline = FALSE, $showPath = FALSE)
1746  {
1747  include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php";
1748  return ilObjSurveyQuestionPool::_getAvailableQuestionpools($use_object_id = TRUE, $could_be_offline, $showPath);
1749  }
1750 
1757  function moveUpQuestion($question_id)
1758  {
1759  $move_questions = array($question_id);
1760  $pages =& $this->getSurveyPages();
1761  $pageindex = -1;
1762  foreach ($pages as $idx => $page)
1763  {
1764  if ($page[0]["question_id"] == $question_id)
1765  {
1766  $pageindex = $idx;
1767  }
1768  }
1769  if ($pageindex > 0)
1770  {
1771  $this->moveQuestions($move_questions, $pages[$pageindex-1][0]["question_id"], 0);
1772  }
1773  else
1774  {
1775  // move up a question in a questionblock
1776  $questions = $this->getSurveyQuestions();
1777  $questions = array_keys($questions);
1778  $index = array_search($question_id, $questions);
1779  if (($index !== FALSE) && ($index > 0))
1780  {
1781  $this->moveQuestions($move_questions, $questions[$index-1], 0);
1782  }
1783  }
1784  }
1785 
1791  public function moveDownQuestion($question_id)
1792  {
1793  $move_questions = array($question_id);
1794  $pages =& $this->getSurveyPages();
1795  $pageindex = -1;
1796  foreach ($pages as $idx => $page)
1797  {
1798  if (($page[0]["question_id"] == $question_id) && (strcmp($page[0]["questionblock_id"], "") == 0))
1799  {
1800  $pageindex = $idx;
1801  }
1802  }
1803  if (($pageindex < count($pages)-1) && ($pageindex >= 0))
1804  {
1805  $this->moveQuestions($move_questions, $pages[$pageindex+1][count($pages[$pageindex+1])-1]["question_id"], 1);
1806  }
1807  else
1808  {
1809  // move down a question in a questionblock
1810  $questions = $this->getSurveyQuestions();
1811  $questions = array_keys($questions);
1812  $index = array_search($question_id, $questions);
1813  if (($index !== FALSE) && ($index < count($questions)-1))
1814  {
1815  $this->moveQuestions($move_questions, $questions[$index+1], 1);
1816  }
1817  }
1818  }
1819 
1826  function moveUpQuestionblock($questionblock_id)
1827  {
1828  $pages =& $this->getSurveyPages();
1829  $move_questions = array();
1830  $pageindex = -1;
1831  foreach ($pages as $idx => $page)
1832  {
1833  if ($page[0]["questionblock_id"] == $questionblock_id)
1834  {
1835  foreach ($page as $pageidx => $question)
1836  {
1837  array_push($move_questions, $question["question_id"]);
1838  }
1839  $pageindex = $idx;
1840  }
1841  }
1842  if ($pageindex > 0)
1843  {
1844  $this->moveQuestions($move_questions, $pages[$pageindex-1][0]["question_id"], 0);
1845  }
1846  }
1847 
1854  function moveDownQuestionblock($questionblock_id)
1855  {
1856  $pages =& $this->getSurveyPages();
1857  $move_questions = array();
1858  $pageindex = -1;
1859  foreach ($pages as $idx => $page)
1860  {
1861  if ($page[0]["questionblock_id"] == $questionblock_id)
1862  {
1863  foreach ($page as $pageidx => $question)
1864  {
1865  array_push($move_questions, $question["question_id"]);
1866  }
1867  $pageindex = $idx;
1868  }
1869  }
1870  if ($pageindex < count($pages)-1)
1871  {
1872  $this->moveQuestions($move_questions, $pages[$pageindex+1][count($pages[$pageindex+1])-1]["question_id"], 1);
1873  }
1874  }
1875 
1884  function moveQuestions($move_questions, $target_index, $insert_mode)
1885  {
1886  $array_pos = array_search($target_index, $this->questions);
1887  if ($insert_mode == 0)
1888  {
1889  $part1 = array_slice($this->questions, 0, $array_pos);
1890  $part2 = array_slice($this->questions, $array_pos);
1891  }
1892  else if ($insert_mode == 1)
1893  {
1894  $part1 = array_slice($this->questions, 0, $array_pos + 1);
1895  $part2 = array_slice($this->questions, $array_pos + 1);
1896  }
1897  foreach ($move_questions as $question_id)
1898  {
1899  if (!(array_search($question_id, $part1) === FALSE))
1900  {
1901  unset($part1[array_search($question_id, $part1)]);
1902  }
1903  if (!(array_search($question_id, $part2) === FALSE))
1904  {
1905  unset($part2[array_search($question_id, $part2)]);
1906  }
1907  }
1908  $part1 = array_values($part1);
1909  $part2 = array_values($part2);
1910  $this->questions = array_values(array_merge($part1, $move_questions, $part2));
1911  foreach ($move_questions as $question_id)
1912  {
1913  $constraints = $this->getConstraints($question_id);
1914  foreach ($constraints as $idx => $constraint)
1915  {
1916  foreach ($part2 as $next_question_id)
1917  {
1918  if ($constraint["question"] == $next_question_id)
1919  {
1920  // constraint concerning a question that follows -> delete constraint
1921  $this->deleteConstraint($constraint["id"]);
1922  }
1923  }
1924  }
1925  }
1926  $this->saveQuestionsToDb();
1927  }
1928 
1935  function removeQuestion($question_id)
1936  {
1937  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
1938  $question =& $this->_instanciateQuestion($question_id);
1939  $question->delete($question_id);
1940  $this->removeConstraintsConcerningQuestion($question_id);
1941  }
1942 
1950  {
1951  global $ilDB;
1952  $result = $ilDB->queryF("SELECT constraint_fi FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s",
1953  array('integer','integer'),
1954  array($question_id, $this->getSurveyId())
1955  );
1956  if ($result->numRows() > 0)
1957  {
1958  $remove_constraints = array();
1959  while ($row = $ilDB->fetchAssoc($result))
1960  {
1961  array_push($remove_constraints, $row["constraint_fi"]);
1962  }
1963  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s",
1964  array('integer','integer'),
1965  array($question_id, $this->getSurveyId())
1966  );
1967  foreach ($remove_constraints as $key => $constraint_id)
1968  {
1969  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_constraint WHERE constraint_id = %s",
1970  array('integer'),
1971  array($constraint_id)
1972  );
1973  }
1974  }
1975  }
1976 
1984  function removeQuestions($remove_questions, $remove_questionblocks)
1985  {
1986  global $ilDB;
1987  $questions =& $this->getSurveyQuestions();
1988  foreach ($questions as $question_id => $data)
1989  {
1990  if (in_array($question_id, $remove_questions) or in_array($data["questionblock_id"], $remove_questionblocks))
1991  {
1992  unset($this->questions[array_search($question_id, $this->questions)]);
1993  $this->removeQuestion($question_id);
1994  }
1995  }
1996  foreach ($remove_questionblocks as $questionblock_id)
1997  {
1998  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk WHERE questionblock_id = %s",
1999  array('integer'),
2000  array($questionblock_id)
2001  );
2002  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s",
2003  array('integer','integer'),
2004  array($questionblock_id, $this->getSurveyId())
2005  );
2006  }
2007  $this->questions = array_values($this->questions);
2008  $this->saveQuestionsToDb();
2009  }
2010 
2017  function unfoldQuestionblocks($questionblocks)
2018  {
2019  global $ilDB;
2020  foreach ($questionblocks as $index)
2021  {
2022  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk WHERE questionblock_id = %s",
2023  array('integer'),
2024  array($index)
2025  );
2026  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s",
2027  array('integer','integer'),
2028  array($index, $this->getSurveyId())
2029  );
2030  }
2031  }
2032 
2039  function &getQuestionblockQuestions($questionblock_id)
2040  {
2041  global $ilDB;
2042  $titles = array();
2043  $result = $ilDB->queryF("SELECT svy_question.title, svy_qblk_qst.question_fi, svy_qblk_qst.survey_fi FROM ".
2044  "svy_qblk, svy_qblk_qst, svy_question WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND " .
2045  "svy_question.question_id = svy_qblk_qst.question_fi AND svy_qblk.questionblock_id = %s",
2046  array('integer'),
2047  array($questionblock_id)
2048  );
2049  $survey_id = "";
2050  while ($row = $ilDB->fetchAssoc($result))
2051  {
2052  $titles[$row["question_fi"]] = $row["title"];
2053  $survey_id = $row["survey_fi"];
2054  }
2055  $result = $ilDB->queryF("SELECT question_fi, sequence FROM svy_svy_qst WHERE survey_fi = %s ORDER BY sequence",
2056  array('integer'),
2057  array($survey_id)
2058  );
2059  $resultarray = array();
2060  $counter = 1;
2061  while ($row = $ilDB->fetchAssoc($result))
2062  {
2063  if (array_key_exists($row["question_fi"], $titles))
2064  {
2065  $resultarray[$counter++] = $titles[$row["question_fi"]];
2066  }
2067  }
2068  return $resultarray;
2069  }
2070 
2077  function &getQuestionblockQuestionIds($questionblock_id)
2078  {
2079  global $ilDB;
2080  $result = $ilDB->queryF("SELECT question_fi FROM svy_qblk_qst WHERE questionblock_fi = %s",
2081  array("integer"),
2082  array($questionblock_id)
2083  );
2084  $ids = array();
2085  if ($result->numRows())
2086  {
2087  while ($data = $ilDB->fetchAssoc($result))
2088  {
2089  array_push($ids, $data['question_fi']);
2090  }
2091  }
2092  return $ids;
2093  }
2094 
2102  function getQuestionblock($questionblock_id)
2103  {
2104  global $ilDB;
2105  $result = $ilDB->queryF("SELECT * FROM svy_qblk WHERE questionblock_id = %s",
2106  array('integer'),
2107  array($questionblock_id)
2108  );
2109  return $ilDB->fetchAssoc($result);
2110  }
2111 
2119  function _getQuestionblock($questionblock_id)
2120  {
2121  global $ilDB;
2122  $result = $ilDB->queryF("SELECT * FROM svy_qblk WHERE questionblock_id = %s",
2123  array('integer'),
2124  array($questionblock_id)
2125  );
2126  $row = $ilDB->fetchAssoc($result);
2127  return $row;
2128  }
2129 
2138  function _addQuestionblock($title = "", $owner = 0)
2139  {
2140  global $ilDB;
2141  $next_id = $ilDB->nextId('svy_qblk');
2142  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk (questionblock_id, title, owner_fi, tstamp) " .
2143  "VALUES (%s, %s, %s, %s)",
2144  array('integer','text','integer','integer'),
2145  array($next_id, $title, $owner, time())
2146  );
2147  return $next_id;
2148  }
2149 
2157  function createQuestionblock($title, $show_questiontext, $questions)
2158  {
2159  global $ilDB;
2160  // if the selected questions are not in a continous selection, move all questions of the
2161  // questionblock at the position of the first selected question
2162  $this->moveQuestions($questions, $questions[0], 0);
2163 
2164  // now save the question block
2165  global $ilUser;
2166  $next_id = $ilDB->nextId('svy_qblk');
2167  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk (questionblock_id, title, show_questiontext, owner_fi, ".
2168  "tstamp) VALUES (%s, %s, %s, %s, %s)",
2169  array('integer','text','text','integer','integer'),
2170  array($next_id, $title, $show_questiontext, $ilUser->getId(), time())
2171  );
2172  if ($affectedRows)
2173  {
2174  $questionblock_id = $next_id;
2175  foreach ($questions as $index)
2176  {
2177  $next_id = $ilDB->nextId('svy_qblk_qst');
2178  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, " .
2179  "question_fi) VALUES (%s, %s, %s, %s)",
2180  array('integer','integer','integer','integer'),
2181  array($next_id, $this->getSurveyId(), $questionblock_id, $index)
2182  );
2183  $this->deleteConstraints($index);
2184  }
2185  }
2186  }
2187 
2195  function modifyQuestionblock($questionblock_id, $title, $show_questiontext)
2196  {
2197  global $ilDB;
2198  $affectedRows = $ilDB->manipulateF("UPDATE svy_qblk SET title = %s, show_questiontext = %s WHERE " .
2199  "questionblock_id = %s",
2200  array('text','text','integer'),
2201  array($title, $show_questiontext, $questionblock_id)
2202  );
2203  }
2204 
2211  function deleteConstraints($question_id)
2212  {
2213  global $ilDB;
2214  $result = $ilDB->queryF("SELECT constraint_fi FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s",
2215  array('integer','integer'),
2216  array($question_id, $this->getSurveyId())
2217  );
2218  $constraints = array();
2219  while ($row = $ilDB->fetchAssoc($result))
2220  {
2221  array_push($constraints, $row["constraint_fi"]);
2222  }
2223  foreach ($constraints as $constraint_id)
2224  {
2225  $this->deleteConstraint($constraint_id);
2226  }
2227  }
2228 
2236  function deleteConstraint($constraint_id)
2237  {
2238  global $ilDB;
2239  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_constraint WHERE constraint_id = %s",
2240  array('integer'),
2241  array($constraint_id)
2242  );
2243  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_constraint WHERE constraint_fi = %s",
2244  array('integer'),
2245  array($constraint_id)
2246  );
2247  }
2248 
2254  public function &getSurveyQuestions($with_answers = false)
2255  {
2256  global $ilDB;
2257  $obligatory_states =& $this->getObligatoryStates();
2258  // get questionblocks
2259  $all_questions = array();
2260  $result = $ilDB->queryF("SELECT svy_qtype.type_tag, svy_qtype.plugin, svy_question.question_id, ".
2261  "svy_svy_qst.heading FROM svy_qtype, svy_question, svy_svy_qst WHERE svy_svy_qst.survey_fi = %s AND " .
2262  "svy_svy_qst.question_fi = svy_question.question_id AND svy_question.questiontype_fi = svy_qtype.questiontype_id " .
2263  "ORDER BY svy_svy_qst.sequence",
2264  array('integer'),
2265  array($this->getSurveyId())
2266  );
2267  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
2268  while ($row = $ilDB->fetchAssoc($result))
2269  {
2270  $add = true;
2271  if ($row["plugin"])
2272  {
2273  if (!$this->isPluginActive($row["type_tag"]))
2274  {
2275  $add = false;
2276  }
2277  }
2278  if ($add)
2279  {
2280  $question =& $this->_instanciateQuestion($row["question_id"]);
2281  $questionrow = $question->_getQuestionDataArray($row["question_id"]);
2282  foreach ($row as $key => $value)
2283  {
2284  $questionrow[$key] = $value;
2285  }
2286  $all_questions[$row["question_id"]] = $questionrow;
2287  $all_questions[$row["question_id"]]["usableForPrecondition"] = $question->usableForPrecondition();
2288  $all_questions[$row["question_id"]]["availableRelations"] = $question->getAvailableRelations();
2289  if (array_key_exists($row["question_id"], $obligatory_states))
2290  {
2291  $all_questions[$row["question_id"]]["obligatory"] = $obligatory_states[$row["question_id"]];
2292  }
2293  }
2294  }
2295  // get all questionblocks
2296  $questionblocks = array();
2297  if (count($all_questions))
2298  {
2299  $result = $ilDB->queryF("SELECT svy_qblk.*, svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst WHERE " .
2300  "svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_qblk_qst.survey_fi = %s " .
2301  "AND " . $ilDB->in('svy_qblk_qst.question_fi', array_keys($all_questions), false, 'integer'),
2302  array('integer'),
2303  array($this->getSurveyId())
2304  );
2305  while ($row = $ilDB->fetchAssoc($result))
2306  {
2307  $questionblocks[$row['question_fi']] = $row;
2308  }
2309  }
2310 
2311  foreach ($all_questions as $question_id => $row)
2312  {
2313  $constraints = $this->getConstraints($question_id);
2314  if (isset($questionblocks[$question_id]))
2315  {
2316  $all_questions[$question_id]["questionblock_title"] = $questionblocks[$question_id]['title'];
2317  $all_questions[$question_id]["questionblock_id"] = $questionblocks[$question_id]['questionblock_id'];
2318  $all_questions[$question_id]["constraints"] = $constraints;
2319  }
2320  else
2321  {
2322  $all_questions[$question_id]["questionblock_title"] = "";
2323  $all_questions[$question_id]["questionblock_id"] = "";
2324  $all_questions[$question_id]["constraints"] = $constraints;
2325  }
2326  if ($with_answers)
2327  {
2328  $answers = array();
2329  $result = $ilDB->queryF("SELECT svy_variable.*, svy_category.title FROM svy_variable, svy_category " .
2330  "WHERE svy_variable.question_fi = %s AND svy_variable.category_fi = svy_category.category_id ".
2331  "ORDER BY sequence ASC",
2332  array('integer'),
2333  array($question_id)
2334  );
2335  if ($result->numRows() > 0)
2336  {
2337  while ($data = $ilDB->fetchAssoc($result))
2338  {
2339  array_push($answers, $data["title"]);
2340  }
2341  }
2342  $all_questions[$question_id]["answers"] = $answers;
2343  }
2344  }
2345  return $all_questions;
2346  }
2347 
2354  function setObligatoryStates($obligatory_questions)
2355  {
2356  global $ilDB;
2357  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE survey_fi = %s",
2358  array('integer'),
2359  array($this->getSurveyId())
2360  );
2361  if ($result->numRows())
2362  {
2363  while ($row = $ilDB->fetchAssoc($result))
2364  {
2365  if (!array_key_exists($row["question_fi"], $obligatory_questions))
2366  {
2367  $obligatory_questions[$row["question_fi"]] = 0;
2368  }
2369  }
2370  }
2371 
2372  // set the obligatory states in the database
2373  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_oblig WHERE survey_fi = %s",
2374  array('integer'),
2375  array($this->getSurveyId())
2376  );
2377 
2378  // set the obligatory states in the database
2379  foreach ($obligatory_questions as $question_fi => $obligatory)
2380  {
2381  $next_id = $ilDB->nextId('svy_qst_oblig');
2382  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qst_oblig (question_obligatory_id, survey_fi, question_fi, " .
2383  "obligatory, tstamp) VALUES (%s, %s, %s, %s, %s)",
2384  array('integer','integer','integer','text','integer'),
2385  array($next_id, $this->getSurveyId(), $question_fi, (strlen($obligatory)) ? $obligatory : 0, time())
2386  );
2387  }
2388  }
2389 
2397  {
2398  global $ilDB;
2399  $obligatory_states = array();
2400  $result = $ilDB->queryF("SELECT * FROM svy_qst_oblig WHERE survey_fi = %s",
2401  array('integer'),
2402  array($this->getSurveyId())
2403  );
2404  if ($result->numRows())
2405  {
2406  while ($row = $ilDB->fetchAssoc($result))
2407  {
2408  $obligatory_states[$row["question_fi"]] = $row["obligatory"];
2409  }
2410  }
2411  return $obligatory_states;
2412  }
2413 
2419  function &getSurveyPages()
2420  {
2421  global $ilDB;
2422  $obligatory_states =& $this->getObligatoryStates();
2423  // get questionblocks
2424  $all_questions = array();
2425  $result = $ilDB->queryF("SELECT svy_question.*, svy_qtype.type_tag, svy_svy_qst.heading FROM " .
2426  "svy_question, svy_qtype, svy_svy_qst WHERE svy_svy_qst.survey_fi = %s AND " .
2427  "svy_svy_qst.question_fi = svy_question.question_id AND svy_question.questiontype_fi = svy_qtype.questiontype_id ".
2428  "ORDER BY svy_svy_qst.sequence",
2429  array('integer'),
2430  array($this->getSurveyId())
2431  );
2432  while ($row = $ilDB->fetchAssoc($result))
2433  {
2434  $all_questions[$row["question_id"]] = $row;
2435  }
2436  // get all questionblocks
2437  $questionblocks = array();
2438  if (count($all_questions))
2439  {
2440  $result = $ilDB->queryF("SELECT svy_qblk.*, svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst ".
2441  "WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_qblk_qst.survey_fi = %s ".
2442  "AND " . $ilDB->in('svy_qblk_qst.question_fi', array_keys($all_questions), false, 'integer'),
2443  array('integer'),
2444  array($this->getSurveyId())
2445  );
2446  while ($row = $ilDB->fetchAssoc($result))
2447  {
2448  $questionblocks[$row['question_fi']] = $row;
2449  }
2450  }
2451 
2452  $all_pages = array();
2453  $pageindex = -1;
2454  $currentblock = "";
2455  foreach ($all_questions as $question_id => $row)
2456  {
2457  if (array_key_exists($question_id, $obligatory_states))
2458  {
2459  $all_questions[$question_id]["obligatory"] = $obligatory_states[$question_id];
2460  }
2461  $constraints = array();
2462  if (isset($questionblocks[$question_id]))
2463  {
2464  if (!$currentblock or ($currentblock != $questionblocks[$question_id]['questionblock_id']))
2465  {
2466  $pageindex++;
2467  }
2468  $all_questions[$question_id]['page'] = $pageindex;
2469  $all_questions[$question_id]["questionblock_title"] = $questionblocks[$question_id]['title'];
2470  $all_questions[$question_id]["questionblock_id"] = $questionblocks[$question_id]['questionblock_id'];
2471  $all_questions[$question_id]["questionblock_show_questiontext"] = $questionblocks[$question_id]['show_questiontext'];
2472  $currentblock = $questionblocks[$question_id]['questionblock_id'];
2473  $constraints = $this->getConstraints($question_id);
2474  $all_questions[$question_id]["constraints"] = $constraints;
2475  }
2476  else
2477  {
2478  $pageindex++;
2479  $all_questions[$question_id]['page'] = $pageindex;
2480  $all_questions[$question_id]["questionblock_title"] = "";
2481  $all_questions[$question_id]["questionblock_id"] = "";
2482  $all_questions[$question_id]["questionblock_show_questiontext"] = 1;
2483  $currentblock = "";
2484  $constraints = $this->getConstraints($question_id);
2485  $all_questions[$question_id]["constraints"] = $constraints;
2486  }
2487  if (!isset($all_pages[$pageindex]))
2488  {
2489  $all_pages[$pageindex] = array();
2490  }
2491  array_push($all_pages[$pageindex], $all_questions[$question_id]);
2492  }
2493  // calculate position percentage for every page
2494  $max = count($all_pages);
2495  $counter = 1;
2496  foreach ($all_pages as $index => $block)
2497  {
2498  foreach ($block as $blockindex => $question)
2499  {
2500  $all_pages[$index][$blockindex]["position"] = $counter / $max;
2501  }
2502  $counter++;
2503  }
2504  return $all_pages;
2505  }
2506 
2515  function getNextPage($active_page_question_id, $direction)
2516  {
2517  $foundpage = -1;
2518  $pages =& $this->getSurveyPages();
2519  if (strcmp($active_page_question_id, "") == 0)
2520  {
2521  return $pages[0];
2522  }
2523  foreach ($pages as $key => $question_array)
2524  {
2525  foreach ($question_array as $question)
2526  {
2527  if ($active_page_question_id == $question["question_id"])
2528  {
2529  $foundpage = $key;
2530  }
2531  }
2532  }
2533  if ($foundpage == -1)
2534  {
2535  // error: page not found
2536  }
2537  else
2538  {
2539  $foundpage += $direction;
2540  if ($foundpage < 0)
2541  {
2542  return 0;
2543  }
2544  if ($foundpage >= count($pages))
2545  {
2546  return 1;
2547  }
2548  return $pages[$foundpage];
2549  }
2550  }
2551 
2558  function &getAvailableQuestionpools($use_obj_id = false, $could_be_offline = false, $showPath = FALSE, $permission = "read")
2559  {
2560  include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php";
2561  return ilObjSurveyQuestionPool::_getAvailableQuestionpools($use_obj_id, $could_be_offline, $showPath, $permission);
2562  }
2563 
2570  {
2571  global $ilDB;
2572 
2573  $result_array = array();
2574  $result = $ilDB->queryF("SELECT svy_constraint.*, svy_relation.* FROM svy_qst_constraint, svy_constraint, ".
2575  "svy_relation WHERE svy_constraint.relation_fi = svy_relation.relation_id AND ".
2576  "svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_constraint.constraint_id = %s",
2577  array('integer'),
2578  array($id)
2579  );
2580  $pc = array();
2581  if ($result->numRows())
2582  {
2583  $pc = $ilDB->fetchAssoc($result);
2584  }
2585  return $pc;
2586  }
2587 
2593  function getConstraints($question_id)
2594  {
2595  global $ilDB;
2596 
2597  $result_array = array();
2598  $result = $ilDB->queryF("SELECT svy_constraint.*, svy_relation.* FROM svy_qst_constraint, svy_constraint, svy_relation ".
2599  "WHERE svy_constraint.relation_fi = svy_relation.relation_id AND ".
2600  "svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_qst_constraint.question_fi = %s ".
2601  "AND svy_qst_constraint.survey_fi = %s",
2602  array('integer','integer'),
2603  array($question_id, $this->getSurveyId())
2604  );
2605  while ($row = $ilDB->fetchAssoc($result))
2606  {
2607  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
2608  $question_type = SurveyQuestion::_getQuestionType($row["question_fi"]);
2609  SurveyQuestion::_includeClass($question_type);
2610  $question = new $question_type();
2611  $question->loadFromDb($row["question_fi"]);
2612  $valueoutput = $question->getPreconditionValueOutput($row["value"]);
2613  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));
2614  }
2615  return $result_array;
2616  }
2617 
2624  {
2625  global $ilDB;
2626  $result_array = array();
2627  $result = $ilDB->queryF("SELECT svy_qst_constraint.question_fi as for_question, svy_constraint.*, svy_relation.* ".
2628  "FROM svy_qst_constraint, svy_constraint, svy_relation WHERE svy_constraint.relation_fi = svy_relation.relation_id ".
2629  "AND svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_qst_constraint.survey_fi = %s",
2630  array('integer'),
2631  array($survey_id)
2632  );
2633  while ($row = $ilDB->fetchAssoc($result))
2634  {
2635  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']));
2636  }
2637  return $result_array;
2638  }
2639 
2640 
2646  function &getVariables($question_id)
2647  {
2648  global $ilDB;
2649 
2650  $result_array = array();
2651  $result = $ilDB->queryF("SELECT svy_variable.*, svy_category.title FROM svy_variable LEFT JOIN ".
2652  "svy_category ON svy_variable.category_fi = svy_category.category_id WHERE svy_variable.question_fi = %s ".
2653  "ORDER BY svy_variable.sequence",
2654  array('integer'),
2655  array($question_id)
2656  );
2657  while ($row = $ilDB->fetchObject($result))
2658  {
2659  $result_array[$row->sequence] = $row;
2660  }
2661  return $result_array;
2662  }
2663 
2672  function addConstraint($if_question_id, $relation, $value, $conjunction)
2673  {
2674  global $ilDB;
2675 
2676  $next_id = $ilDB->nextId('svy_constraint');
2677  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_constraint (constraint_id, question_fi, relation_fi, value, conjunction) VALUES ".
2678  "(%s, %s, %s, %s, %s)",
2679  array('integer','integer','integer','float', 'integer'),
2680  array($next_id, $if_question_id, $relation, $value, $conjunction)
2681  );
2682  if ($affectedRows)
2683  {
2684  return $next_id;
2685  }
2686  else
2687  {
2688  return null;
2689  }
2690  }
2691 
2692 
2699  public function addConstraintToQuestion($to_question_id, $constraint_id)
2700  {
2701  global $ilDB;
2702 
2703  $next_id = $ilDB->nextId('svy_qst_constraint');
2704  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qst_constraint (question_constraint_id, survey_fi, question_fi, ".
2705  "constraint_fi) VALUES (%s, %s, %s, %s)",
2706  array('integer','integer','integer','integer'),
2707  array($next_id, $this->getSurveyId(), $to_question_id, $constraint_id)
2708  );
2709  }
2710 
2721  function updateConstraint($precondition_id, $if_question_id, $relation, $value, $conjunction)
2722  {
2723  global $ilDB;
2724  $affectedRows = $ilDB->manipulateF("UPDATE svy_constraint SET question_fi = %s, relation_fi = %s, value = %s, conjunction = %s ".
2725  "WHERE constraint_id = %s",
2726  array('integer','integer','float','integer','integer'),
2727  array($if_question_id, $relation, $value, $conjunction, $precondition_id)
2728  );
2729  }
2730 
2731  public function updateConjunctionForQuestions($questions, $conjunction)
2732  {
2733  global $ilDB;
2734  foreach ($questions as $question_id)
2735  {
2736  $affectedRows = $ilDB->manipulateF("UPDATE svy_constraint SET conjunction = %s ".
2737  "WHERE constraint_id IN (SELECT constraint_fi FROM svy_qst_constraint WHERE svy_qst_constraint.question_fi = %s)",
2738  array('integer','integer'),
2739  array($conjunction, $question_id)
2740  );
2741  }
2742  }
2743 
2749  function getAllRelations($short_as_key = false)
2750  {
2751  global $ilDB;
2752 
2753  $result_array = array();
2754  $result = $ilDB->query("SELECT * FROM svy_relation");
2755  while ($row = $ilDB->fetchAssoc($result))
2756  {
2757  if ($short_as_key)
2758  {
2759  $result_array[$row["shortname"]] = array("short" => $row["shortname"], "long" => $row["longname"], "id" => $row["relation_id"]);
2760  }
2761  else
2762  {
2763  $result_array[$row["relation_id"]] = array("short" => $row["shortname"], "long" => $row["longname"]);
2764  }
2765  }
2766  return $result_array;
2767  }
2768 
2772  public function disinviteAllUsers()
2773  {
2774  global $ilDB;
2775  $result = $ilDB->queryF("SELECT user_fi FROM svy_inv_usr WHERE survey_fi = %s",
2776  array('integer'),
2777  array($this->getSurveyId())
2778  );
2779  while ($row = $ilDB->fetchAssoc($result))
2780  {
2781  $this->disinviteUser($row['user_fi']);
2782  }
2783  }
2784 
2790  public function disinviteUser($user_id)
2791  {
2792  global $ilDB;
2793 
2794  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_inv_usr WHERE survey_fi = %s AND user_fi = %s",
2795  array('integer','integer'),
2796  array($this->getSurveyId(), $user_id)
2797  );
2798  include_once './Services/User/classes/class.ilObjUser.php';
2799  ilObjUser::_dropDesktopItem($user_id, $this->getRefId(), "svy");
2800  }
2801 
2808  function inviteUser($user_id)
2809  {
2810  global $ilDB;
2811 
2812  $result = $ilDB->queryF("SELECT user_fi FROM svy_inv_usr WHERE user_fi = %s AND survey_fi = %s",
2813  array('integer','integer'),
2814  array($user_id, $this->getSurveyId())
2815  );
2816  if ($result->numRows() < 1)
2817  {
2818  $next_id = $ilDB->nextId('svy_inv_usr');
2819  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_inv_usr (invited_user_id, survey_fi, user_fi, tstamp) " .
2820  "VALUES (%s, %s, %s, %s)",
2821  array('integer','integer','integer','integer'),
2822  array($next_id, $this->getSurveyId(), $user_id, time())
2823  );
2824  }
2825  if ($this->getInvitation() == INVITATION_ON)
2826  {
2827  include_once './Services/User/classes/class.ilObjUser.php';
2828  ilObjUser::_addDesktopItem($user_id, $this->getRefId(), "svy");
2829  }
2830  }
2831 
2838  function inviteGroup($group_id)
2839  {
2840  global $ilAccess;
2841  $invited = 0;
2842  include_once "./Modules/Group/classes/class.ilObjGroup.php";
2843  $group = new ilObjGroup($group_id);
2844  $members = $group->getGroupMemberIds();
2845  foreach ($members as $user_id)
2846  {
2847  if ($ilAccess->checkAccessOfUser($user_id, "read", "", $this->getRefId(), "svy", $this->getId()))
2848  {
2849  $this->inviteUser($user_id);
2850  if ($this->getInvitation() == INVITATION_ON)
2851  {
2852  include_once './Services/User/classes/class.ilObjUser.php';
2853  ilObjUser::_addDesktopItem($user_id, $this->getRefId(), "svy");
2854  }
2855  }
2856  }
2857  return $invited;
2858  }
2859 
2866  function inviteRole($role_id)
2867  {
2868  global $rbacreview;
2869  global $ilAccess;
2870  $invited = 0;
2871  $members = $rbacreview->assignedUsers($role_id);
2872  foreach ($members as $user_id)
2873  {
2874  if ($ilAccess->checkAccessOfUser($user_id, "read", "", $this->getRefId(), "svy", $this->getId()))
2875  {
2876  $this->inviteUser($user_id);
2877  if ($this->getInvitation() == INVITATION_ON)
2878  {
2879  include_once './Services/User/classes/class.ilObjUser.php';
2880  ilObjUser::_addDesktopItem($user_id, $this->getRefId(), "svy");
2881  }
2882  }
2883  }
2884  return $invited;
2885  }
2886 
2893  function &getInvitedUsers()
2894  {
2895  global $ilDB;
2896 
2897  $result_array = array();
2898  $result = $ilDB->queryF("SELECT user_fi FROM svy_inv_usr WHERE survey_fi = %s",
2899  array('integer'),
2900  array($this->getSurveyId())
2901  );
2902  while ($row = $ilDB->fetchAssoc($result))
2903  {
2904  array_push($result_array, $row["user_fi"]);
2905  }
2906  return $result_array;
2907  }
2908 
2916  function deleteWorkingData($question_id, $active_id)
2917  {
2918  global $ilDB;
2919 
2920  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE question_fi = %s AND active_fi = %s",
2921  array('integer','integer'),
2922  array($question_id, $active_id)
2923  );
2924  }
2925 
2934  function loadWorkingData($question_id, $active_id)
2935  {
2936  global $ilDB;
2937  $result_array = array();
2938  $result = $ilDB->queryF("SELECT * FROM svy_answer WHERE question_fi = %s AND active_fi = %s",
2939  array('integer','integer'),
2940  array($question_id, $active_id)
2941  );
2942  if ($result->numRows() >= 1)
2943  {
2944  while ($row = $ilDB->fetchAssoc($result))
2945  {
2946  array_push($result_array, $row);
2947  }
2948  return $result_array;
2949  }
2950  else
2951  {
2952  return $result_array;
2953  }
2954  }
2955 
2962  function fillSurveyForUser($user_id = ANONYMOUS_USER_ID)
2963  {
2964  global $ilDB;
2965  // create an anonymous key
2966  $anonymous_id = $this->createNewAccessCode();
2967  $this->saveUserAccessCode($user_id, $anonymous_id);
2968  // create the survey_finished dataset and set the survey finished already
2969  $active_id = $ilDB->nextId('svy_finished');
2970  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_finished (finished_id, survey_fi, user_fi, anonymous_id, state, tstamp) ".
2971  "VALUES (%s, %s, %s, %s, %s, %s)",
2972  array('integer','integer','integer','text','text','integer'),
2973  array($active_id, $this->getSurveyId(), $user_id, $anonymous_id, 1, time())
2974  );
2975  // fill the questions randomly
2976  $pages =& $this->getSurveyPages();
2977  foreach ($pages as $key => $question_array)
2978  {
2979  foreach ($question_array as $question)
2980  {
2981  // instanciate question
2982  require_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
2983  $question =& SurveyQuestion::_instanciateQuestion($question["question_id"]);
2984  $question->saveRandomData($active_id);
2985  }
2986  }
2987  }
2988 
2995  function startSurvey($user_id, $anonymous_id)
2996  {
2997  global $ilUser;
2998  global $ilDB;
2999 
3000  if ($this->getAnonymize() && (strlen($anonymous_id) == 0)) return;
3001 
3002  if (strcmp($user_id, "") == 0)
3003  {
3004  if ($user_id == ANONYMOUS_USER_ID)
3005  {
3006  $user_id = 0;
3007  }
3008  }
3009  $next_id = $ilDB->nextId('svy_finished');
3010  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_finished (finished_id, survey_fi, user_fi, anonymous_id, state, tstamp) ".
3011  "VALUES (%s, %s, %s, %s, %s, %s)",
3012  array('integer','integer','integer','text','text','integer'),
3013  array($next_id, $this->getSurveyId(), $user_id, $anonymous_id, 0, time())
3014  );
3015  return $next_id;
3016  }
3017 
3024  function finishSurvey($user_id, $anonymize_id)
3025  {
3026  global $ilDB;
3027 
3028  if ($this->getAnonymize())
3029  {
3030  $affectedRows = $ilDB->manipulateF("UPDATE svy_finished SET state = %s, user_fi = %s, tstamp = %s ".
3031  "WHERE survey_fi = %s AND anonymous_id = %s",
3032  array('text','integer','integer','integer','text'),
3033  array(1, $user_id, time(), $this->getSurveyId(), $anonymize_id)
3034  );
3035  }
3036  else
3037  {
3038  $affectedRows = $ilDB->manipulateF("UPDATE svy_finished SET state = %s, tstamp = %s WHERE survey_fi = %s AND user_fi = %s",
3039  array('text','integer','integer','integer'),
3040  array(1, time(), $this->getSurveyId(), $user_id)
3041  );
3042  }
3043  if ($this->getMailNotification())
3044  {
3045  $this->sendNotificationMail($user_id, $anonymize_id);
3046  }
3047  }
3048 
3056  function setPage($finished_id, $page_id)
3057  {
3058  global $ilDB;
3059 
3060  $affectedRows = $ilDB->manipulateF("UPDATE svy_finished SET lastpage = %s WHERE finished_id = %s",
3061  array('integer','integer'),
3062  array(($page_id) ? $page_id : 0, $finished_id)
3063  );
3064  }
3065 
3066  function sendNotificationMail($user_id, $anonymize_id)
3067  {
3068  include_once "./Services/User/classes/class.ilObjUser.php";
3069  include_once "./Services/Mail/classes/class.ilMail.php";
3070  $mail = new ilMail(ANONYMOUS_USER_ID);
3071  $recipients = preg_split('/,/', $this->mailaddresses);
3072  foreach ($recipients as $recipient)
3073  {
3074  $messagetext = $this->mailparticipantdata;
3075  $data = ilObjUser::_getUserData(array($user_id));
3076  foreach ($data[0] as $key => $value)
3077  {
3078  if ($this->getAnonymize())
3079  {
3080  $messagetext = str_replace('[' . $key . ']', '', $messagetext);
3081  }
3082  else
3083  {
3084  $messagetext = str_replace('[' . $key . ']', $value, $messagetext);
3085  }
3086  }
3087  $active_id = $this->getActiveID($user_id, $anonymize_id);
3088  $messagetext .= ((strlen($messagetext)) ? "\n\n\n" : '') . $this->lng->txt('results') . "\n\n". $this->getParticipantTextResults($active_id);
3089  if (($not_sent != 1) || $data['sent'] == 0)
3090  {
3091  $res = $mail->sendMail(
3092  $recipient, // to
3093  "", // cc
3094  "", // bcc
3095  $this->lng->txt('finished_mail_subject') . ': ' . $this->getTitle(), // subject
3096  $messagetext, // message
3097  array(), // attachments
3098  array('normal') // type
3099  );
3100  }
3101  }
3102  }
3103 
3104  protected function getParticipantTextResults($active_id)
3105  {
3106  $textresult = "";
3107  $userResults =& $this->getUserSpecificResults();
3108  $questions =& $this->getSurveyQuestions(true);
3109  $questioncounter = 1;
3110  foreach ($questions as $question_id => $question_data)
3111  {
3112  $textresult .= $questioncounter++ . ". " . $question_data["title"] . "\n";
3113  $found = $userResults[$question_id][$active_id];
3114  $text = "";
3115  if (is_array($found))
3116  {
3117  $text = implode("\n", $found);
3118  }
3119  else
3120  {
3121  $text = $found;
3122  }
3123  if (strlen($text) == 0) $text = $this->lng->txt("skipped");
3124  $text = str_replace("<br />", "\n", $text);
3125  $textresult .= $text . "\n\n";
3126  }
3127  return $textresult;
3128  }
3129 
3131  {
3132  $counter = 0;
3133  $questions =& $this->getSurveyQuestions();
3134  $counter++;
3135  foreach ($questions as $data)
3136  {
3137  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
3138  $question = SurveyQuestion::_instanciateQuestion($data["question_id"]);
3139 
3140  $eval = $this->getCumulatedResults($question);
3141  }
3142  }
3143 
3151  function isAllowedToTakeMultipleSurveys($userid = "")
3152  {
3153  $result = FALSE;
3154  if ($this->getAnonymize())
3155  {
3156  if ($this->isAccessibleWithoutCode())
3157  {
3158  if (strlen($username) == 0)
3159  {
3160  global $ilUser;
3161  $userid = $ilUser->getId();
3162  }
3163  global $ilSetting;
3164  $surveysetting = new ilSetting("survey");
3165  $allowedUsers = strlen($surveysetting->get("multiple_survey_users")) ? explode(",",$surveysetting->get("multiple_survey_users")) : array();
3166  if (in_array($userid, $allowedUsers))
3167  {
3168  $result = TRUE;
3169  }
3170  }
3171  }
3172  return $result;
3173  }
3174 
3182  function isSurveyStarted($user_id, $anonymize_id)
3183  {
3184  global $ilDB;
3185 
3186  if ($this->getAnonymize())
3187  {
3188  if ((($user_id != ANONYMOUS_USER_ID) && (strlen($anonymize_id) == 0)) && (!($this->isAccessibleWithoutCode() && $this->isAllowedToTakeMultipleSurveys())))
3189  {
3190  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
3191  array('integer','integer'),
3192  array($this->getSurveyId(), $user_id)
3193  );
3194  }
3195  else
3196  {
3197  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s AND anonymous_id = %s",
3198  array('integer','text'),
3199  array($this->getSurveyId(), $anonymize_id)
3200  );
3201  }
3202  }
3203  else
3204  {
3205  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
3206  array('integer','integer'),
3207  array($this->getSurveyId(), $user_id)
3208  );
3209  }
3210  if ($result->numRows() == 0)
3211  {
3212  return false;
3213  }
3214  else
3215  {
3216  $row = $ilDB->fetchAssoc($result);
3217  $_SESSION["finished_id"][$this->getId()] = $row["finished_id"];
3218  return (int)$row["state"];
3219  }
3220  }
3221 
3229  function getActiveID($user_id, $anonymize_id)
3230  {
3231  global $ilDB;
3232 
3233  if ($this->getAnonymize())
3234  {
3235  if ((($user_id != ANONYMOUS_USER_ID) && (strlen($anonymize_id) == 0)) && (!($this->isAccessibleWithoutCode() && $this->isAllowedToTakeMultipleSurveys())))
3236  {
3237  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
3238  array('integer','integer'),
3239  array($this->getSurveyId(), $user_id)
3240  );
3241  }
3242  else
3243  {
3244  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s AND anonymous_id = %s",
3245  array('integer','text'),
3246  array($this->getSurveyId(), $anonymize_id)
3247  );
3248  }
3249  }
3250  else
3251  {
3252  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
3253  array('integer','integer'),
3254  array($this->getSurveyId(), $user_id)
3255  );
3256  }
3257  if ($result->numRows() == 0)
3258  {
3259  return false;
3260  }
3261  else
3262  {
3263  $row = $ilDB->fetchAssoc($result);
3264  return $row["finished_id"];
3265  }
3266  }
3267 
3275  function getLastActivePage($active_id)
3276  {
3277  global $ilDB;
3278  $result = $ilDB->queryF("SELECT lastpage FROM svy_finished WHERE finished_id = %s",
3279  array('integer'),
3280  array($active_id)
3281  );
3282  if ($result->numRows() == 0)
3283  {
3284  return "";
3285  }
3286  else
3287  {
3288  $row = $ilDB->fetchAssoc($result);
3289  return ($row["lastpage"]) ? $row["lastpage"] : '';
3290  }
3291  }
3292 
3301  function checkConstraint($constraint_data, $working_data)
3302  {
3303  if (count($working_data) == 0)
3304  {
3305  return 0;
3306  }
3307 
3308  if ((count($working_data) == 1) and (strcmp($working_data[0]["value"], "") == 0))
3309  {
3310  return 0;
3311  }
3312 
3313  $found = false;
3314  foreach ($working_data as $data)
3315  {
3316  switch ($constraint_data["short"])
3317  {
3318  case "<":
3319  if ($data["value"] < $constraint_data["value"])
3320  {
3321  $found = true;
3322  }
3323  break;
3324 
3325  case "<=":
3326  if ($data["value"] <= $constraint_data["value"])
3327  {
3328  $found = true;
3329  }
3330  break;
3331 
3332  case "=":
3333  if ($data["value"] == $constraint_data["value"])
3334  {
3335  $found = true;
3336  }
3337  break;
3338 
3339  case "<>":
3340  if ($data["value"] <> $constraint_data["value"])
3341  {
3342  $found = true;
3343  }
3344  break;
3345 
3346  case ">=":
3347  if ($data["value"] >= $constraint_data["value"])
3348  {
3349  $found = true;
3350  }
3351  break;
3352 
3353  case ">":
3354  if ($data["value"] > $constraint_data["value"])
3355  {
3356  $found = true;
3357  }
3358  break;
3359  }
3360  if ($found)
3361  {
3362  break;
3363  }
3364  }
3365 
3366  return (int)$found;
3367  }
3368 
3370  {
3371  global $ilDB;
3372 
3373  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
3374  array('integer'),
3375  array($survey_id)
3376  );
3377  return ($result->numRows()) ? true : false;
3378  }
3379 
3387  {
3388  global $ilDB, $ilLog;
3389 
3390  $users = array();
3391  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s",
3392  array('integer'),
3393  array($this->getSurveyId())
3394  );
3395  if ($result->numRows())
3396  {
3397  while ($row = $ilDB->fetchAssoc($result))
3398  {
3399  array_push($users, $row["finished_id"]);
3400  }
3401  }
3402  return $users;
3403  }
3404 
3412  {
3413  global $ilDB;
3414 
3415  $users = array();
3416  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s",
3417  array('integer'),
3418  array($this->getSurveyId())
3419  );
3420  if ($result->numRows())
3421  {
3422  while ($row = $ilDB->fetchAssoc($result))
3423  {
3424  array_push($users, $row);
3425  }
3426  }
3427  $evaluation = array();
3428  $questions =& $this->getSurveyQuestions();
3429  foreach ($questions as $question_id => $question_data)
3430  {
3431  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
3432  $question_type = SurveyQuestion::_getQuestionType($question_id);
3433  SurveyQuestion::_includeClass($question_type);
3434  $question = new $question_type();
3435  $question->loadFromDb($question_id);
3436  $data =& $question->getUserAnswers($this->getSurveyId());
3437  $evaluation[$question_id] = $data;
3438  }
3439  return $evaluation;
3440  }
3441 
3449  function getUserDataFromActiveId($active_id)
3450  {
3451  global $ilDB;
3452 
3453  $surveySetting = new ilSetting("survey");
3454  $use_anonymous_id = array_key_exists("use_anonymous_id", $_GET) ? $_GET["use_anonymous_id"] : $surveySetting->get("use_anonymous_id");
3455  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE finished_id = %s",
3456  array('integer'),
3457  array($active_id)
3458  );
3459  $row = array();
3460  $foundrows = $result->numRows();
3461  if ($foundrows)
3462  {
3463  $row = $ilDB->fetchAssoc($result);
3464  }
3465  $name = ($use_anonymous_id) ? $row["anonymous_id"] : $this->lng->txt("anonymous");
3466  $userdata = array(
3467  "fullname" => $name,
3468  "sortname" => $name,
3469  "firstname" => "",
3470  "lastname" => "",
3471  "login" => "",
3472  "gender" => "",
3473  "active_id" => "$active_id"
3474  );
3475  if ($foundrows)
3476  {
3477  if (($row["user_fi"] > 0) && ($row["user_fi"] != ANONYMOUS_USER_ID) && ($this->getAnonymize() == 0))
3478  {
3479  include_once './Services/User/classes/class.ilObjUser.php';
3480  if (strlen(ilObjUser::_lookupLogin($row["user_fi"])) == 0)
3481  {
3482  $userdata["fullname"] = $this->lng->txt("deleted_user");
3483  }
3484  else
3485  {
3486  $user = new ilObjUser($row["user_fi"]);
3487  $userdata["fullname"] = $user->getFullname();
3488  $gender = $user->getGender();
3489  if (strlen($gender) == 1) $gender = $this->lng->txt("gender_$gender");
3490  $userdata["gender"] = $gender;
3491  $userdata["firstname"] = $user->getFirstname();
3492  $userdata["lastname"] = $user->getLastname();
3493  $userdata["sortname"] = $user->getLastname() . ", " . $user->getFirstname();
3494  $userdata["login"] = $user->getLogin();
3495  }
3496  }
3497  }
3498  return $userdata;
3499  }
3500 
3510  function &getEvaluationByUser($questions, $active_id)
3511  {
3512  global $ilDB;
3513 
3514  // collect all answers
3515  $answers = array();
3516  $result = $ilDB->queryF("SELECT * FROM svy_answer WHERE active_fi = %s",
3517  array('integer'),
3518  array($active_id)
3519  );
3520  while ($row = $ilDB->fetchAssoc($result))
3521  {
3522  if (!is_array($answers[$row["question_fi"]]))
3523  {
3524  $answers[$row["question_fi"]] = array();
3525  }
3526  array_push($answers[$row["question_fi"]], $row);
3527  }
3528  $userdata = $this->getUserDataFromActiveId($active_id);
3529  $resultset = array(
3530  "name" => $userdata["fullname"],
3531  "gender" => $userdata["gender"],
3532  "answers" => array()
3533  );
3534  foreach ($questions as $key => $question)
3535  {
3536  if (array_key_exists($key, $answers))
3537  {
3538  $resultset["answers"][$key] = $answers[$key];
3539  }
3540  else
3541  {
3542  $resultset["answers"][$key] = array();
3543  }
3544  sort($resultset["answers"][$key]);
3545  }
3546  return $resultset;
3547  }
3548 
3557  function getCumulatedResults(&$question)
3558  {
3559  global $ilDB;
3560 
3561  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
3562  array('integer'),
3563  array($this->getSurveyId())
3564  );
3565  $nr_of_users = $result->numRows();
3566 
3567  $result_array =& $question->getCumulatedResults($this->getSurveyId(), $nr_of_users);
3568  return $result_array;
3569  }
3570 
3579  {
3580  global $ilDB;
3581 
3582  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
3583  array('integer'),
3584  array($survey_id)
3585  );
3586  return $result->numRows();
3587  }
3588 
3589  function &getQuestions($question_ids)
3590  {
3591  $result_array = array();
3592  $result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag FROM svy_question, svy_qtype WHERE ".
3593  "svy_question.questiontype_fi = svy_qtype.questiontype_id AND svy_question.tstamp > 0 AND ".
3594  $ilDB->in('svy_question.question_id', $question_ids, false, 'integer'));
3595  while ($row = $ilDB->fetchAssoc($result))
3596  {
3597  array_push($result_array, $row);
3598  }
3599  return $result_array;
3600  }
3601 
3607  function getQuestionsTable($arrFilter)
3608  {
3609  global $ilUser;
3610  global $ilDB;
3611  $where = "";
3612  if (is_array($arrFilter))
3613  {
3614  if (array_key_exists('title', $arrFilter) && strlen($arrFilter['title']))
3615  {
3616  $where .= " AND " . $ilDB->like('svy_question.title', 'text', "%%" . $arrFilter['title'] . "%%");
3617  }
3618  if (array_key_exists('description', $arrFilter) && strlen($arrFilter['description']))
3619  {
3620  $where .= " AND " . $ilDB->like('svy_question.description', 'text', "%%" . $arrFilter['description'] . "%%");
3621  }
3622  if (array_key_exists('author', $arrFilter) && strlen($arrFilter['author']))
3623  {
3624  $where .= " AND " . $ilDB->like('svy_question.author', 'text', "%%" . $arrFilter['author'] . "%%");
3625  }
3626  if (array_key_exists('type', $arrFilter) && strlen($arrFilter['type']))
3627  {
3628  $where .= " AND svy_qtype.type_tag = " . $ilDB->quote($arrFilter['type'], 'text');
3629  }
3630  if (array_key_exists('spl', $arrFilter) && strlen($arrFilter['spl']))
3631  {
3632  $where .= " AND svy_question.obj_fi = " . $ilDB->quote($arrFilter['spl'], 'integer');
3633  }
3634  }
3635 
3636  $spls =& $this->getAvailableQuestionpools($use_obj_id = TRUE, $could_be_offline = FALSE, $showPath = FALSE);
3637  $forbidden = "";
3638  $forbidden = " AND " . $ilDB->in('svy_question.obj_fi', array_keys($spls), false, 'integer');
3639  $forbidden .= " AND svy_question.complete = " . $ilDB->quote("1", 'text');
3640  $existing = "";
3641  $existing_questions =& $this->getExistingQuestions();
3642  if (count($existing_questions))
3643  {
3644  $existing = " AND " . $ilDB->in('svy_question.question_id', $existing_questions, true, 'integer');
3645  }
3646 
3647  include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php";
3649 
3650  $query_result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag, svy_qtype.plugin, object_reference.ref_id FROM svy_question, svy_qtype, object_reference WHERE svy_question.original_id IS NULL$forbidden$existing AND svy_question.obj_fi = object_reference.obj_id AND svy_question.tstamp > 0 AND svy_question.questiontype_fi = svy_qtype.questiontype_id " . $where);
3651 
3652  $rows = array();
3653  if ($query_result->numRows())
3654  {
3655  while ($row = $ilDB->fetchAssoc($query_result))
3656  {
3657  $row['ttype'] = $trans[$row['type_tag']];
3658  if ($row["plugin"])
3659  {
3660  if ($this->isPluginActive($row["type_tag"]))
3661  {
3662  array_push($rows, $row);
3663  }
3664  }
3665  else
3666  {
3667  array_push($rows, $row);
3668  }
3669  }
3670  }
3671  return $rows;
3672  }
3673 
3679  function getQuestionblocksTable($arrFilter)
3680  {
3681  global $ilUser;
3682  global $ilDB;
3683  $where = "";
3684  if (is_array($arrFilter))
3685  {
3686  if (array_key_exists('title', $arrFilter) && strlen($arrFilter['title']))
3687  {
3688  $where .= " AND " . $ilDB->like('svy_qblk.title', 'text', "%%" . $arrFilter['title'] . "%%");
3689  }
3690  }
3691 
3692  $query_result = $ilDB->query("SELECT svy_qblk.*, svy_svy.obj_fi FROM svy_qblk , svy_qblk_qst, svy_svy WHERE ".
3693  "svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_svy.survey_id = svy_qblk_qst.survey_fi ".
3694  "$where GROUP BY svy_qblk.questionblock_id, svy_qblk.title, svy_qblk.show_questiontext, svy_qblk.owner_fi, svy_qblk.tstamp, svy_svy.obj_fi");
3695  $rows = array();
3696  if ($query_result->numRows())
3697  {
3698  $surveys = ilObject::_getObjectsDataForType('svy', true);
3699  $surveytitles = array();
3700  foreach ($surveys as $data)
3701  {
3702  $surveytitles[$data['id']] = $data['title'];
3703  }
3704  while ($row = $ilDB->fetchAssoc($query_result))
3705  {
3706  $questions_array =& $this->getQuestionblockQuestions($row["questionblock_id"]);
3707  $counter = 1;
3708  foreach ($questions_array as $key => $value)
3709  {
3710  $questions_array[$key] = "$counter. $value";
3711  $counter++;
3712  }
3713  if (strlen($surveytitles[$row["obj_fi"]])) // only questionpools which are not in trash
3714  {
3715  $rows[$row["questionblock_id"]] = array(
3716  "questionblock_id" => $row["questionblock_id"],
3717  "title" => $row["title"],
3718  "svy" => $surveytitles[$row["obj_fi"]],
3719  "contains" => join($questions_array, ", "),
3720  "owner" => $row["owner_fi"]
3721  );
3722  }
3723  }
3724  }
3725  return $rows;
3726  }
3727 
3734  function toXML()
3735  {
3736  include_once("./Services/Xml/classes/class.ilXmlWriter.php");
3737  $a_xml_writer = new ilXmlWriter;
3738  // set xml header
3739  $a_xml_writer->xmlHeader();
3740  $attrs = array(
3741  "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
3742  "xsi:noNamespaceSchemaLocation" => "http://www.ilias.de/download/xsd/ilias_survey_3_8.xsd"
3743  );
3744  $a_xml_writer->xmlStartTag("surveyobject", $attrs);
3745  $attrs = array(
3746  "id" => $this->getSurveyId(),
3747  "title" => $this->getTitle()
3748  );
3749  $a_xml_writer->xmlStartTag("survey", $attrs);
3750 
3751  $a_xml_writer->xmlElement("description", NULL, $this->getDescription());
3752  $a_xml_writer->xmlElement("author", NULL, $this->getAuthor());
3753  $a_xml_writer->xmlStartTag("objectives");
3754  $attrs = array(
3755  "label" => "introduction"
3756  );
3757  $this->addMaterialTag($a_xml_writer, $this->getIntroduction(), TRUE, TRUE, $attrs);
3758  $attrs = array(
3759  "label" => "outro"
3760  );
3761  $this->addMaterialTag($a_xml_writer, $this->getOutro(), TRUE, TRUE, $attrs);
3762  $a_xml_writer->xmlEndTag("objectives");
3763 
3764  if ($this->getAnonymize())
3765  {
3766  $attribs = array("enabled" => "1");
3767  }
3768  else
3769  {
3770  $attribs = array("enabled" => "0");
3771  }
3772  $a_xml_writer->xmlElement("anonymisation", $attribs);
3773  $a_xml_writer->xmlStartTag("restrictions");
3774  if ($this->getAnonymize() == 2)
3775  {
3776  $attribs = array("type" => "free");
3777  }
3778  else
3779  {
3780  $attribs = array("type" => "restricted");
3781  }
3782  $a_xml_writer->xmlElement("access", $attribs);
3783  if ($this->getStartDateEnabled())
3784  {
3785  $attrs = array("type" => "date");
3786  $a_xml_writer->xmlElement("startingtime", $attrs, sprintf("%04d-%02d-%02dT%02d:%02d:00", $this->getStartYear(), $this->getStartMonth(), $this->getStartDay(), $this->getStartHour(), $this->getStartMinute()));
3787  }
3788  if ($this->getEndDateEnabled())
3789  {
3790  $attrs = array("type" => "date");
3791  $a_xml_writer->xmlElement("endingtime", $attrs, sprintf("%04d-%02d-%02dT%02d:%02d:00", $this->getEndYear(), $this->getEndMonth(), $this->getEndDay(), $this->getEndHour(), $this->getEndMinute()));
3792  }
3793  $a_xml_writer->xmlEndTag("restrictions");
3794 
3795  // constraints
3796  $pages =& $this->getSurveyPages();
3797  $hasconstraints = FALSE;
3798  foreach ($pages as $question_array)
3799  {
3800  foreach ($question_array as $question)
3801  {
3802  if (count($question["constraints"]))
3803  {
3804  $hasconstraints = TRUE;
3805  }
3806  }
3807  }
3808 
3809  if ($hasconstraints)
3810  {
3811  $a_xml_writer->xmlStartTag("constraints");
3812  foreach ($pages as $question_array)
3813  {
3814  foreach ($question_array as $question)
3815  {
3816  if (count($question["constraints"]))
3817  {
3818  // found constraints
3819  foreach ($question["constraints"] as $constraint)
3820  {
3821  $attribs = array(
3822  "sourceref" => $question["question_id"],
3823  "destref" => $constraint["question"],
3824  "relation" => $constraint["short"],
3825  "value" => $constraint["value"]
3826  );
3827  $a_xml_writer->xmlElement("constraint", $attribs);
3828  }
3829  }
3830  }
3831  }
3832  $a_xml_writer->xmlEndTag("constraints");
3833  }
3834 
3835  // add the rest of the preferences in qtimetadata tags, because there is no correspondent definition in QTI
3836  $a_xml_writer->xmlStartTag("metadata");
3837 
3838  $a_xml_writer->xmlStartTag("metadatafield");
3839  $a_xml_writer->xmlElement("fieldlabel", NULL, "evaluation_access");
3840  $a_xml_writer->xmlElement("fieldentry", NULL, $this->getEvaluationAccess());
3841  $a_xml_writer->xmlEndTag("metadatafield");
3842 
3843  $a_xml_writer->xmlStartTag("metadatafield");
3844  $a_xml_writer->xmlElement("fieldlabel", NULL, "status");
3845  $a_xml_writer->xmlElement("fieldentry", NULL, $this->getStatus());
3846  $a_xml_writer->xmlEndTag("metadatafield");
3847 
3848  $a_xml_writer->xmlStartTag("metadatafield");
3849  $a_xml_writer->xmlElement("fieldlabel", NULL, "display_question_titles");
3850  $a_xml_writer->xmlElement("fieldentry", NULL, $this->getShowQuestionTitles());
3851  $a_xml_writer->xmlEndTag("metadatafield");
3852 
3853  $a_xml_writer->xmlStartTag("metadatafield");
3854  $a_xml_writer->xmlElement("fieldlabel", NULL, "SCORM");
3855  include_once "./Services/MetaData/classes/class.ilMD.php";
3856  $md = new ilMD($this->getId(),0, $this->getType());
3857  $writer = new ilXmlWriter();
3858  $md->toXml($writer);
3859  $metadata = $writer->xmlDumpMem();
3860  $a_xml_writer->xmlElement("fieldentry", NULL, $metadata);
3861  $a_xml_writer->xmlEndTag("metadatafield");
3862 
3863  $a_xml_writer->xmlEndTag("metadata");
3864  $a_xml_writer->xmlEndTag("survey");
3865 
3866  $attribs = array("id" => $this->getId());
3867  $a_xml_writer->xmlStartTag("surveyquestions", $attribs);
3868  // add questionblock descriptions
3869  $obligatory_states =& $this->getObligatoryStates();
3870  foreach ($pages as $question_array)
3871  {
3872  if (count($question_array) > 1)
3873  {
3874  $attribs = array("id" => $question_array[0]["question_id"]);
3875  $attribs = array("showQuestiontext" => $question_array[0]["questionblock_show_questiontext"]);
3876  $a_xml_writer->xmlStartTag("questionblock", $attribs);
3877  if (strlen($question_array[0]["questionblock_title"]))
3878  {
3879  $a_xml_writer->xmlElement("questionblocktitle", NULL, $question_array[0]["questionblock_title"]);
3880  }
3881  }
3882  foreach ($question_array as $question)
3883  {
3884  if (strlen($question["heading"]))
3885  {
3886  $a_xml_writer->xmlElement("textblock", NULL, $question["heading"]);
3887  }
3888  $questionObject =& $this->_instanciateQuestion($question["question_id"]);
3889  if ($questionObject !== FALSE) $questionObject->insertXML($a_xml_writer, FALSE, $obligatory_states[$question["question_id"]]);
3890  }
3891  if (count($question_array) > 1)
3892  {
3893  $a_xml_writer->xmlEndTag("questionblock");
3894  }
3895  }
3896 
3897  $a_xml_writer->xmlEndTag("surveyquestions");
3898  $a_xml_writer->xmlEndTag("surveyobject");
3899  $xml = $a_xml_writer->xmlDumpMem(FALSE);
3900  return $xml;
3901  }
3902 
3910  function &_instanciateQuestion($question_id)
3911  {
3912  if ($question_id < 1) return FALSE;
3913  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
3914  $question_type = SurveyQuestion::_getQuestionType($question_id);
3915  if (strlen($question_type) == 0) return FALSE;
3916  SurveyQuestion::_includeClass($question_type);
3917  $question = new $question_type();
3918  $question->loadFromDb($question_id);
3919  return $question;
3920  }
3921 
3928  function locateImportFiles($a_dir)
3929  {
3930  if (!is_dir($a_dir) || is_int(strpos($a_dir, "..")))
3931  {
3932  return;
3933  }
3934  $importDirectory = "";
3935  $xmlFile = "";
3936 
3937  $current_dir = opendir($a_dir);
3938  $files = array();
3939  while($entryname = readdir($current_dir))
3940  {
3941  $files[] = $entryname;
3942  }
3943 
3944  foreach($files as $file)
3945  {
3946  if(is_dir($a_dir."/".$file) and ($file != "." and $file!=".."))
3947  {
3948  // found directory created by zip
3949  $importDirectory = $a_dir."/".$file;
3950  }
3951  }
3952  closedir($current_dir);
3953  if (strlen($importDirectory))
3954  {
3955  // find the xml file
3956  $current_dir = opendir($importDirectory);
3957  $files = array();
3958  while($entryname = readdir($current_dir))
3959  {
3960  $files[] = $entryname;
3961  }
3962  foreach($files as $file)
3963  {
3964  if(@is_file($importDirectory."/".$file) && ($file != "." && $file!="..") && (strcmp(strtolower(substr($file, -4, 4)), ".xml") == 0))
3965  {
3966  // found xml file
3967  $xmlFile = $importDirectory."/".$file;
3968  }
3969  }
3970  }
3971  return array("dir" => $importDirectory, "xml" => $xmlFile);
3972  }
3973 
3980  function importObject($file_info, $svy_qpl_id)
3981  {
3982  // check if file was uploaded
3983  $source = $file_info["tmp_name"];
3984  $error = "";
3985  if (($source == 'none') || (!$source) || $file_info["error"] > UPLOAD_ERR_OK)
3986  {
3987  $error = $this->lng->txt("import_no_file_selected");
3988  }
3989  // check correct file type
3990  $isXml = FALSE;
3991  $isZip = FALSE;
3992  if ((strcmp($file_info["type"], "text/xml") == 0) || (strcmp($file_info["type"], "application/xml") == 0))
3993  {
3994  $isXml = TRUE;
3995  }
3996  if (strpos($file_info["type"], "zip") !== FALSE)
3997  {
3998  $isZip = TRUE;
3999  }
4000  if (!$isXml && !$isZip)
4001  {
4002  $error = $this->lng->txt("import_wrong_file_type");
4003  global $ilLog;
4004  $ilLog->write("Survey: Import error. Filetype was \"" . $file_info["type"] ."\"");
4005  }
4006  if (strlen($error) == 0)
4007  {
4008  // import file as a survey
4009  $import_dir = $this->getImportDirectory();
4010  $import_subdir = "";
4011  $importfile = "";
4012  include_once "./Services/Utilities/classes/class.ilUtil.php";
4013  if ($isZip)
4014  {
4015  $importfile = $import_dir."/".$file_info["name"];
4016  ilUtil::moveUploadedFile($source, $file_info["name"], $importfile);
4017  ilUtil::unzip($importfile);
4018  $found = $this->locateImportFiles($import_dir);
4019  if (!((strlen($found["dir"]) > 0) && (strlen($found["xml"]) > 0)))
4020  {
4021  $error = $this->lng->txt("wrong_import_file_structure");
4022  return $error;
4023  }
4024  $importfile = $found["xml"];
4025  $import_subdir = $found["dir"];
4026  }
4027  else
4028  {
4029  $importfile = tempnam($import_dir, "survey_import");
4030  ilUtil::moveUploadedFile($source, $file_info["name"], $importfile);
4031  }
4032  $fh = fopen($importfile, "r");
4033  if (!$fh)
4034  {
4035  $error = $this->lng->txt("import_error_opening_file");
4036  return $error;
4037  }
4038  $xml = fread($fh, filesize($importfile));
4039  $result = fclose($fh);
4040  if (!$result)
4041  {
4042  $error = $this->lng->txt("import_error_closing_file");
4043  return $error;
4044  }
4045 
4046  unset($_SESSION["import_mob_xhtml"]);
4047  if (strpos($xml, "questestinterop"))
4048  {
4049  include_once "./Services/Survey/classes/class.SurveyImportParserPre38.php";
4050  include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php";
4051  $spl = new ilObjSurveyQuestionPool($svy_qpl_id, FALSE);
4052  $import = new SurveyImportParserPre38($spl, "", TRUE);
4053  $import->setSurveyObject($this);
4054  $import->setXMLContent($xml);
4055  $import->startParsing();
4056  }
4057  else
4058  {
4059  include_once "./Services/Survey/classes/class.SurveyImportParser.php";
4060  include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php";
4061  $spl = new ilObjSurveyQuestionPool($svy_qpl_id, FALSE);
4062  $import = new SurveyImportParser($spl, "", TRUE);
4063  $import->setSurveyObject($this);
4064  $import->setXMLContent($xml);
4065  $import->startParsing();
4066  }
4067 
4068  if (is_array($_SESSION["import_mob_xhtml"]))
4069  {
4070  include_once "./Services/MediaObjects/classes/class.ilObjMediaObject.php";
4071  include_once "./Services/RTE/classes/class.ilRTE.php";
4072  include_once "./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php";
4073  foreach ($_SESSION["import_mob_xhtml"] as $mob)
4074  {
4075  $importfile = $import_subdir . "/" . $mob["uri"];
4076  if (file_exists($importfile))
4077  {
4078  $media_object =& ilObjMediaObject::_saveTempFileAsMediaObject(basename($importfile), $importfile, FALSE);
4079  ilObjMediaObject::_saveUsage($media_object->getId(), "svy:html", $this->getId());
4080  $this->setIntroduction(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $this->getIntroduction()));
4081  $this->setOutro(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $this->getOutro()));
4082  }
4083  else
4084  {
4085  global $ilLog;
4086  $ilLog->write("Error: Could not open XHTML mob file for test introduction during test import. File $importfile does not exist!");
4087  }
4088  }
4091  $this->saveToDb();
4092  }
4093 
4094  // delete import directory
4096  }
4097  return $error;
4098  }
4099 
4108  public function cloneObject($a_target_id,$a_copy_id = 0)
4109  {
4110  global $ilDB;
4111 
4112  $this->loadFromDb();
4113 
4114  // Copy settings
4115  $newObj = parent::cloneObject($a_target_id,$a_copy_id);
4116  $this->cloneMetaData($newObj);
4117 
4118 
4119  $newObj->setAuthor($this->getAuthor());
4120  $newObj->setIntroduction($this->getIntroduction());
4121  $newObj->setOutro($this->getOutro());
4122  $newObj->setStatus($this->getStatus());
4123  $newObj->setEvaluationAccess($this->getEvaluationAccess());
4124  $newObj->setStartDate($this->getStartDate());
4125  $newObj->setStartDateEnabled($this->getStartDateEnabled());
4126  $newObj->setEndDate($this->getEndDate());
4127  $newObj->setEndDateEnabled($this->getEndDateEnabled());
4128  $newObj->setInvitation($this->getInvitation());
4129  $newObj->setInvitationMode($this->getInvitationMode());
4130  $newObj->setAnonymize($this->getAnonymize());
4131  $newObj->setShowQuestionTitles($this->getShowQuestionTitles());
4132 
4133 
4134  $question_pointer = array();
4135  // clone the questions
4136  $mapping = array();
4137  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
4138  foreach ($this->questions as $key => $question_id)
4139  {
4140  $question = ilObjSurvey::_instanciateQuestion($question_id);
4141  $question->id = -1;
4142  $original_id = SurveyQuestion::_getOriginalId($question_id);
4143  $question->saveToDb($original_id);
4144  $newObj->questions[$key] = $question->getId();
4145  $question_pointer[$question_id] = $question->getId();
4146  $mapping[$question_id] = $question->getId();
4147  }
4148 
4149  $newObj->saveToDb();
4150  $newObj->cloneTextblocks($mapping);
4151 
4152  // clone the questionblocks
4153  $questionblocks = array();
4154  $questionblock_questions = array();
4155  $result = $ilDB->queryF("SELECT * FROM svy_qblk_qst WHERE survey_fi = %s",
4156  array('integer'),
4157  array($this->getSurveyId())
4158  );
4159  if ($result->numRows() > 0)
4160  {
4161  while ($row = $ilDB->fetchAssoc($result))
4162  {
4163  array_push($questionblock_questions, $row);
4164  $questionblocks[$row["questionblock_fi"]] = $row["questionblock_fi"];
4165  }
4166  }
4167  // create new questionblocks
4168  foreach ($questionblocks as $key => $value)
4169  {
4170  $questionblock = ilObjSurvey::_getQuestionblock($key);
4171  $questionblock_id = ilObjSurvey::_addQuestionblock($questionblock["title"], $questionblock["owner_fi"]);
4172  $questionblocks[$key] = $questionblock_id;
4173  }
4174  // create new questionblock questions
4175  foreach ($questionblock_questions as $key => $value)
4176  {
4177  $next_id = $ilDB->nextId('svy_qblk_qst');
4178  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, question_fi) ".
4179  "VALUES (%s, %s, %s, %s)",
4180  array('integer','integer','integer','integer'),
4181  array($next_id, $newObj->getSurveyId(), $questionblocks[$value["questionblock_fi"]], $question_pointer[$value["question_fi"]])
4182  );
4183  }
4184 
4185  // clone the constraints
4186  $constraints = ilObjSurvey::_getConstraints($this->getSurveyId());
4187  $newConstraints = array();
4188  foreach ($constraints as $key => $constraint)
4189  {
4190  if (!array_key_exists($constraint['id'], $newConstraints))
4191  {
4192  $constraint_id = $newObj->addConstraint($question_pointer[$constraint["question"]], $constraint["relation_id"], $constraint["value"], $constraint['conjunction']);
4193  $newConstraints[$constraint['id']] = $constraint_id;
4194  }
4195  $newObj->addConstraintToQuestion($question_pointer[$constraint["for_question"]], $newConstraints[$constraint['id']]);
4196  }
4197 
4198  // clone the obligatory states
4199  $result = $ilDB->queryF("SELECT * FROM svy_qst_oblig WHERE survey_fi = %s",
4200  array('integer'),
4201  array($this->getSurveyId())
4202  );
4203  if ($result->numRows() > 0)
4204  {
4205  while ($row = $ilDB->fetchAssoc($result))
4206  {
4207  $next_id = $ilDB->nextId('svy_qst_oblig');
4208  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qst_oblig (question_obligatory_id, survey_fi, question_fi, ".
4209  "obligatory, tstamp) VALUES (%s, %s, %s, %s, %s)",
4210  array('integer','integer','integer','text','integer'),
4211  array($next_id, $newObj->getSurveyId(), $question_pointer[$row["question_fi"]], $row["obligatory"], time())
4212  );
4213  }
4214  }
4215  return $newObj;
4216  }
4217 
4218  function getTextblock($question_id)
4219  {
4220  global $ilDB;
4221  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE question_fi = %s",
4222  array('integer'),
4223  array($question_id)
4224  );
4225  if ($result->numRows())
4226  {
4227  $row = $ilDB->fetchAssoc($result);
4228  return $row["heading"];
4229  }
4230  else
4231  {
4232  return "";
4233  }
4234  }
4235 
4241  function cloneTextblocks($mapping)
4242  {
4243  foreach ($mapping as $original_id => $new_id)
4244  {
4245  $textblock = $this->getTextblock($original_id);
4246  include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php";
4247  $this->saveHeading(ilUtil::stripSlashes($textblock, TRUE, ilObjAdvancedEditing::_getUsedHTMLTagsAsString("survey")), $new_id);
4248  }
4249  }
4250 
4257  {
4258  include_once "./Services/Utilities/classes/class.ilUtil.php";
4259  $svy_data_dir = ilUtil::getDataDir()."/svy_data";
4260  ilUtil::makeDir($svy_data_dir);
4261  if(!is_writable($svy_data_dir))
4262  {
4263  $this->ilias->raiseError("Survey Data Directory (".$svy_data_dir
4264  .") not writeable.",$this->ilias->error_obj->FATAL);
4265  }
4266 
4267  // create learning module directory (data_dir/lm_data/lm_<id>)
4268  $svy_dir = $svy_data_dir."/svy_".$this->getId();
4269  ilUtil::makeDir($svy_dir);
4270  if(!@is_dir($svy_dir))
4271  {
4272  $this->ilias->raiseError("Creation of Survey Directory failed.",$this->ilias->error_obj->FATAL);
4273  }
4274  // create Export subdirectory (data_dir/lm_data/lm_<id>/Export)
4275  $export_dir = $svy_dir."/export";
4276  ilUtil::makeDir($export_dir);
4277  if(!@is_dir($export_dir))
4278  {
4279  $this->ilias->raiseError("Creation of Export Directory failed.",$this->ilias->error_obj->FATAL);
4280  }
4281  }
4282 
4287  {
4288  include_once "./Services/Utilities/classes/class.ilUtil.php";
4289  $export_dir = ilUtil::getDataDir()."/svy_data"."/svy_".$this->getId()."/export";
4290 
4291  return $export_dir;
4292  }
4293 
4298  {
4299  // quit if import dir not available
4300  if (!@is_dir($dir) or
4301  !is_writeable($dir))
4302  {
4303  return array();
4304  }
4305 
4306  // open directory
4307  $dir = dir($dir);
4308 
4309  // initialize array
4310  $file = array();
4311 
4312  // get files and save the in the array
4313  while ($entry = $dir->read())
4314  {
4315  if ($entry != "." and
4316  $entry != ".." and
4317  ereg("^[0-9]{10}_{2}[0-9]+_{2}(survey__)*[0-9]+\.xml|zip\$", $entry))
4318  {
4319  $file[] = $entry;
4320  }
4321  }
4322 
4323  // close import directory
4324  $dir->close();
4325  // sort files
4326  sort ($file);
4327  reset ($file);
4328 
4329  return $file;
4330  }
4331 
4338  {
4339  include_once "./Services/Utilities/classes/class.ilUtil.php";
4340  $svy_data_dir = ilUtil::getDataDir()."/svy_data";
4341  ilUtil::makeDir($svy_data_dir);
4342 
4343  if(!is_writable($svy_data_dir))
4344  {
4345  $this->ilias->raiseError("Survey Data Directory (".$svy_data_dir
4346  .") not writeable.",$this->ilias->error_obj->FATAL);
4347  }
4348 
4349  // create test directory (data_dir/svy_data/svy_<id>)
4350  $svy_dir = $svy_data_dir."/svy_".$this->getId();
4351  ilUtil::makeDir($svy_dir);
4352  if(!@is_dir($svy_dir))
4353  {
4354  $this->ilias->raiseError("Creation of Survey Directory failed.",$this->ilias->error_obj->FATAL);
4355  }
4356 
4357  // create import subdirectory (data_dir/svy_data/svy_<id>/import)
4358  $import_dir = $svy_dir."/import";
4359  ilUtil::makeDir($import_dir);
4360  if(!@is_dir($import_dir))
4361  {
4362  $this->ilias->raiseError("Creation of Import Directory failed.",$this->ilias->error_obj->FATAL);
4363  }
4364  }
4365 
4370  {
4371  include_once "./Services/Utilities/classes/class.ilUtil.php";
4372  $import_dir = ilUtil::getDataDir()."/svy_data".
4373  "/svy_".$this->getId()."/import";
4374  if (!is_dir($import_dir))
4375  {
4376  ilUtil::makeDirParents($import_dir);
4377  }
4378  if(@is_dir($import_dir))
4379  {
4380  return $import_dir;
4381  }
4382  else
4383  {
4384  return false;
4385  }
4386  }
4387 
4388  function saveHeading($heading = "", $insertbefore)
4389  {
4390  global $ilDB;
4391  if ($heading)
4392  {
4393  $affectedRows = $ilDB->manipulateF("UPDATE svy_svy_qst SET heading=%s WHERE survey_fi=%s AND question_fi=%s",
4394  array('text','integer','integer'),
4395  array($heading, $this->getSurveyId(), $insertbefore)
4396  );
4397  }
4398  else
4399  {
4400  $affectedRows = $ilDB->manipulateF("UPDATE svy_svy_qst SET heading=%s WHERE survey_fi=%s AND question_fi=%s",
4401  array('text','integer','integer'),
4402  array(NULL, $this->getSurveyId(), $insertbefore)
4403  );
4404  }
4405  }
4406 
4407  function isAnonymousKey($key)
4408  {
4409  global $ilDB;
4410 
4411  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_anonymous WHERE survey_key = %s AND survey_fi = %s",
4412  array('text','integer'),
4413  array($key, $this->getSurveyId())
4414  );
4415  return ($result->numRows() == 1) ? true : false;
4416  }
4417 
4418  function getUserSurveyCode($user_id)
4419  {
4420  global $ilDB;
4421 
4422  if (($user_id == ANONYMOUS_USER_ID) || (($this->isAccessibleWithoutCode() && $this->isAllowedToTakeMultipleSurveys()))) return "";
4423  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
4424  array('integer','integer'),
4425  array($this->getSurveyId(), $user_id)
4426  );
4427  if ($result->numRows() == 1)
4428  {
4429  $row = $ilDB->fetchAssoc($result);
4430  return $row["anonymous_id"];
4431  }
4432  else
4433  {
4434  return "";
4435  }
4436  }
4437 
4439  {
4440  global $ilDB;
4441 
4442  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE anonymous_id = %s AND survey_fi = %s",
4443  array('text','integer'),
4444  array($key, $this->getSurveyId())
4445  );
4446  return ($result->numRows() == 1) ? true : false;
4447  }
4448 
4449  function checkSurveyCode($code)
4450  {
4451  if ($this->isAnonymousKey($code))
4452  {
4453  if ($this->isSurveyStarted("", $code) == 1)
4454  {
4455  return false;
4456  }
4457  else
4458  {
4459  return true;
4460  }
4461  }
4462  else
4463  {
4464  return false;
4465  }
4466  }
4467 
4475  {
4476  global $ilDB;
4477 
4478  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_anonymous WHERE survey_fi = %s AND user_key IS NULL",
4479  array('integer'),
4480  array($this->getSurveyId())
4481  );
4482  return $result->numRows();
4483  }
4484 
4492  function getSurveyCodesForExport($a_array)
4493  {
4494  global $ilDB, $ilUser;
4495 
4496  $result = $ilDB->queryF("SELECT svy_anonymous.*, svy_finished.state FROM svy_anonymous ".
4497  "LEFT JOIN svy_finished ON svy_anonymous.survey_key = svy_finished.anonymous_id ".
4498  "WHERE svy_anonymous.survey_fi = %s AND svy_anonymous.user_key IS NULL",
4499  array('integer'),
4500  array($this->getSurveyId())
4501  );
4502  $export = "";
4503  $default_lang = $ilUser->getPref("survey_code_language");
4504  $lang = (strlen($default_lang)) ? "&lang=" . $default_lang : "";
4505  while ($row = $ilDB->fetchAssoc($result))
4506  {
4507  if (in_array($row["survey_key"], $a_array) || (count($a_array) == 0))
4508  {
4509  $export .= $row["survey_key"] . ",";
4510 
4511  // No relative (today, tomorrow...) dates in export.
4512  $date = new ilDate($row['tstamp'],IL_CAL_UNIX);
4513  $created = $date->get(IL_CAL_DATE);
4514  $export .= "$created,";
4515  if ($this->isSurveyCodeUsed($row["survey_key"]))
4516  {
4517  $export .= "1,";
4518  }
4519  else
4520  {
4521  $export .= "0,";
4522  }
4523  $url = ILIAS_HTTP_PATH."/goto.php?cmd=infoScreen&target=svy_".$this->getRefId() . "&client_id=" . CLIENT_ID . "&accesscode=".$row["survey_key"].$lang;
4524  $export .= $url . "\n";
4525  }
4526  }
4527  return $export;
4528  }
4529 
4537  public function &getSurveyCodesTableData($lang = "en")
4538  {
4539  global $ilDB;
4540 
4541  include_once "./classes/class.ilFormat.php";
4542  if (strlen($lang) == 0) $lang = "en";
4543 
4544  $order = "ORDER BY tstamp, survey_key ASC";
4545  $codes = array();
4546  $result = $ilDB->queryF("SELECT svy_anonymous.anonymous_id, svy_anonymous.survey_key, svy_anonymous.survey_fi, ".
4547  "svy_anonymous.tstamp, svy_finished.state FROM svy_anonymous LEFT JOIN svy_finished ".
4548  "ON svy_anonymous.survey_key = svy_finished.anonymous_id WHERE svy_anonymous.survey_fi = %s ".
4549  "AND svy_anonymous.user_key IS NULL $order",
4550  array('integer'),
4551  array($this->getSurveyId())
4552  );
4553  if ($result->numRows() > 0)
4554  {
4555  while ($row = $ilDB->fetchAssoc($result))
4556  {
4557  $created = ilDatePresentation::formatDate(new ilDateTime($row["tstamp"],IL_CAL_UNIX));
4558  $url = "";
4559 
4560  $state = 0;
4561  if ($this->isSurveyCodeUsed($row["survey_key"]))
4562  {
4563  $state = 1;
4564  }
4565  else
4566  {
4567  $addlang = "";
4568  if (strlen($lang))
4569  {
4570  $addlang = "&amp;lang=$lang";
4571  }
4572  $href = ILIAS_HTTP_PATH."/goto.php?cmd=infoScreen&target=svy_".$this->getRefId() . "&amp;client_id=" . CLIENT_ID . "&amp;accesscode=".$row["survey_key"].$addlang;
4573  $url = $this->lng->txt("survey_code_url_name");
4574  }
4575  array_push($codes, array('code' => $row["survey_key"], 'date' => $created, 'used' => $state, 'url' => $url, 'href' => $href));
4576  }
4577  }
4578  return $codes;
4579  }
4580 
4581  function isSurveyCodeUsed($code)
4582  {
4583  global $ilDB;
4584  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s AND anonymous_id = %s",
4585  array('integer','text'),
4586  array($this->getSurveyId(), $code)
4587  );
4588  return ($result->numRows() > 0) ? true : false;
4589  }
4590 
4591  function isSurveyCodeUnique($code)
4592  {
4593  global $ilDB;
4594  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_anonymous WHERE survey_fi = %s AND survey_key = %s",
4595  array('integer','text'),
4596  array($this->getSurveyId(), $code)
4597  );
4598  return ($result->numRows() > 0) ? false : true;
4599  }
4600 
4601  function createSurveyCodes($nrOfCodes)
4602  {
4603  global $ilDB;
4604  for ($i = 0; $i < $nrOfCodes; $i++)
4605  {
4606  $anonymize_key = $this->createNewAccessCode();
4607  $next_id = $ilDB->nextId('svy_anonymous');
4608  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, tstamp) ".
4609  "VALUES (%s, %s, %s, %s)",
4610  array('integer','text','integer','integer'),
4611  array($next_id, $anonymize_key, $this->getSurveyId(), time())
4612  );
4613  }
4614  }
4615 
4617  {
4618  global $ilDB;
4619  foreach ($data as $dataset)
4620  {
4621  $anonymize_key = $this->createNewAccessCode();
4622  $next_id = $ilDB->nextId('svy_anonymous');
4623  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, externaldata, tstamp) ".
4624  "VALUES (%s, %s, %s, %s, %s)",
4625  array('integer','text','integer','text','integer'),
4626  array($next_id, $anonymize_key, $this->getSurveyId(), serialize($dataset), time())
4627  );
4628  }
4629  }
4630 
4631  function sendCodes($not_sent, $subject, $message)
4632  {
4633  include_once "./Services/Mail/classes/class.ilMail.php";
4634  $user_id = $this->getOwner();
4635  $mail = new ilMail($user_id);
4636  $recipients = $this->getExternalCodeRecipients();
4637  foreach ($recipients as $data)
4638  {
4639  $messagetext = $message;
4640  $url = ILIAS_HTTP_PATH."/goto.php?cmd=infoScreen&target=svy_".$this->getRefId() . "&amp;client_id=" . CLIENT_ID . "&amp;accesscode=".$data["code"];
4641  $messagetext = str_replace('[url]', "<" . $url . ">", $messagetext);
4642  foreach ($data as $key => $value)
4643  {
4644  $messagetext = str_replace('[' . $key . ']', $value, $messagetext);
4645  }
4646  if (($not_sent != 1) || $data['sent'] == 0)
4647  {
4648  $res = $mail->sendMail(
4649  $data['email'], // to
4650  "", // cc
4651  "", // bcc
4652  $subject, // subject
4653  $messagetext, // message
4654  array(), // attachments
4655  array('normal') // type
4656  );
4657  }
4658  }
4659 
4660  global $ilDB;
4661  $affectedRows = $ilDB->manipulateF("UPDATE svy_anonymous SET sent = %s WHERE survey_fi = %s AND externaldata IS NOT NULL",
4662  array('integer','integer'),
4663  array(1, $this->getSurveyId())
4664  );
4665  }
4666 
4668  {
4669  global $ilDB;
4670  $result = $ilDB->queryF("SELECT survey_key code, externaldata, sent FROM svy_anonymous WHERE survey_fi = %s AND externaldata IS NOT NULL",
4671  array('integer'),
4672  array($this->getSurveyId())
4673  );
4674  $res = array();
4675  while ($row = $ilDB->fetchAssoc($result))
4676  {
4677  $externaldata = unserialize($row['externaldata']);
4678  $externaldata['code'] = $row['code'];
4679  $externaldata['sent'] = $row['sent'];
4680  array_push($res, $externaldata);
4681  }
4682  return $res;
4683  }
4684 
4690  function deleteSurveyCode($survey_code)
4691  {
4692  global $ilDB;
4693 
4694  if (strlen($survey_code) > 0)
4695  {
4696  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_anonymous WHERE survey_fi = %s AND survey_key = %s",
4697  array('integer', 'text'),
4698  array($this->getSurveyId(), $survey_code)
4699  );
4700  }
4701  }
4702 
4709  function getUserAccessCode($user_id)
4710  {
4711  global $ilDB;
4712  $access_code = "";
4713  $result = $ilDB->queryF("SELECT survey_key FROM svy_anonymous WHERE survey_fi = %s AND user_key = %s",
4714  array('integer','text'),
4715  array($this->getSurveyId(), md5($user_id))
4716  );
4717  if ($result->numRows())
4718  {
4719  $row = $ilDB->fetchAssoc($result);
4720  $access_code = $row["survey_key"];
4721  }
4722  return $access_code;
4723  }
4724 
4731  function saveUserAccessCode($user_id, $access_code)
4732  {
4733  global $ilDB;
4734  $next_id = $ilDB->nextId('svy_anonymous');
4735  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, user_key, tstamp) ".
4736  "VALUES (%s, %s, %s, %s, %s)",
4737  array('integer','text', 'integer', 'text', 'integer'),
4738  array($next_id, $access_code, $this->getSurveyId(), md5($user_id), time())
4739  );
4740  }
4741 
4748  {
4749  // create a 5 character code
4750  $codestring = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
4751  mt_srand();
4752  $code = "";
4753  for ($i = 1; $i <=5; $i++)
4754  {
4755  $index = mt_rand(0, strlen($codestring)-1);
4756  $code .= substr($codestring, $index, 1);
4757  }
4758  // verify it against the database
4759  while (!$this->isSurveyCodeUnique($code))
4760  {
4761  $code = $this->createNewAccessCode();
4762  }
4763  return $code;
4764  }
4765 
4766 
4777  function &processCSVRow($row, $quoteAll = FALSE, $separator = ";")
4778  {
4779  $resultarray = array();
4780  foreach ($row as $rowindex => $entry)
4781  {
4782  if(is_array($entry))
4783  {
4784  $entry = implode("/", $entry);
4785  }
4786  $surround = FALSE;
4787  if ($quoteAll)
4788  {
4789  $surround = TRUE;
4790  }
4791  if (strpos($entry, "\"") !== FALSE)
4792  {
4793  $entry = str_replace("\"", "\"\"", $entry);
4794  $surround = TRUE;
4795  }
4796  if (strpos($entry, $separator) !== FALSE)
4797  {
4798  $surround = TRUE;
4799  }
4800  // replace all CR LF with LF (for Excel for Windows compatibility
4801  $entry = str_replace(chr(13).chr(10), chr(10), $entry);
4802  if ($surround)
4803  {
4804  $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
4805  }
4806  else
4807  {
4808  $resultarray[$rowindex] = utf8_decode($entry);
4809  }
4810  }
4811  return $resultarray;
4812  }
4813 
4814  function _getLastAccess($finished_id)
4815  {
4816  global $ilDB;
4817 
4818  $result = $ilDB->queryF("SELECT tstamp FROM svy_answer WHERE active_fi = %s ORDER BY tstamp DESC",
4819  array('integer'),
4820  array($finished_id)
4821  );
4822  if ($result->numRows())
4823  {
4824  $row = $ilDB->fetchAssoc($result);
4825  return $row["tstamp"];
4826  }
4827  else
4828  {
4829  $result = $ilDB->queryF("SELECT tstamp FROM svy_finished WHERE finished_id = %s",
4830  array('integer'),
4831  array($finished_id)
4832  );
4833  if ($result->numRows())
4834  {
4835  $row = $ilDB->fetchAssoc($result);
4836  return $row["tstamp"];
4837  }
4838  }
4839  return "";
4840  }
4841 
4848  function prepareTextareaOutput($txt_output)
4849  {
4850  include_once "./Services/Utilities/classes/class.ilUtil.php";
4851  return ilUtil::prepareTextareaOutput($txt_output, $prepare_for_latex_output);
4852  }
4853 
4861  function isHTML($a_text)
4862  {
4863  if (preg_match("/<[^>]*?>/", $a_text))
4864  {
4865  return TRUE;
4866  }
4867  else
4868  {
4869  return FALSE;
4870  }
4871  }
4872 
4881  function addMaterialTag(&$a_xml_writer, $a_material, $close_material_tag = TRUE, $add_mobs = TRUE, $attribs = NULL)
4882  {
4883  include_once "./Services/RTE/classes/class.ilRTE.php";
4884  include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php");
4885 
4886  $a_xml_writer->xmlStartTag("material", $attribs);
4887  $attrs = array(
4888  "type" => "text/plain"
4889  );
4890  if ($this->isHTML($a_material))
4891  {
4892  $attrs["type"] = "text/xhtml";
4893  }
4894  $mattext = ilRTE::_replaceMediaObjectImageSrc($a_material, 0);
4895  $a_xml_writer->xmlElement("mattext", $attrs, $mattext);
4896 
4897  if ($add_mobs)
4898  {
4899  $mobs = ilObjMediaObject::_getMobsOfObject("svy:html", $this->getId());
4900  foreach ($mobs as $mob)
4901  {
4902  $mob_id = "il_" . IL_INST_ID . "_mob_" . $mob;
4903  if (strpos($mattext, $mob_id) !== FALSE)
4904  {
4905  $mob_obj =& new ilObjMediaObject($mob);
4906  $imgattrs = array(
4907  "label" => $mob_id,
4908  "uri" => "objects/" . "il_" . IL_INST_ID . "_mob_" . $mob . "/" . $mob_obj->getTitle()
4909  );
4910  $a_xml_writer->xmlElement("matimage", $imgattrs, NULL);
4911  }
4912  }
4913  }
4914  if ($close_material_tag) $a_xml_writer->xmlEndTag("material");
4915  }
4916 
4926  {
4927  if ($this->getAnonymize() != ANONYMIZE_OFF)
4928  {
4929  if ($this->surveyCodeSecurity == FALSE)
4930  {
4931  return TRUE;
4932  }
4933  }
4934  return FALSE;
4935  }
4936 
4944  function processPrintoutput2FO($print_output)
4945  {
4946  $print_output = str_replace("&nbsp;", "&#160;", $print_output);
4947  $print_output = str_replace("&otimes;", "X", $print_output);
4948  $xsl = file_get_contents("./Modules/Survey/xml/question2fo.xsl");
4949  $args = array( '/_xml' => $print_output, '/_xsl' => $xsl );
4950  $xh = xslt_create();
4951  $params = array();
4952  $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", NULL, $args, $params);
4953  xslt_error($xh);
4954  xslt_free($xh);
4955  global $ilLog; $ilLog->write($output);
4956  return $output;
4957  }
4958 
4965  function deliverPDFfromFO($fo)
4966  {
4967  global $ilLog;
4968 
4969  include_once "./Services/Utilities/classes/class.ilUtil.php";
4970  $fo_file = ilUtil::ilTempnam() . ".fo";
4971  $fp = fopen($fo_file, "w"); fwrite($fp, $fo); fclose($fp);
4972 
4973  include_once './Services/WebServices/RPC/classes/class.ilRpcClientFactory.php';
4974  try
4975  {
4976  $pdf_base64 = ilRpcClientFactory::factory('RPCTransformationHandler')->ilFO2PDF($fo);
4977  ilUtil::deliverData($pdf_base64->scalar, ilUtil::getASCIIFilename($this->getTitle()) . ".pdf", "application/pdf");
4978  return true;
4979  }
4980  catch(XML_RPC2_FaultException $e)
4981  {
4982  $ilLog->write(__METHOD__.': '.$e->getMessage());
4983  return false;
4984  }
4985  catch(Exception $e)
4986  {
4987  $ilLog->write(__METHOD__.': '.$e->getMessage());
4988  return false;
4989  }
4990 
4991  /*
4992  include_once "./Services/Transformation/classes/class.ilFO2PDF.php";
4993  $fo2pdf = new ilFO2PDF();
4994  $fo2pdf->setFOString($fo);
4995  $result = $fo2pdf->send();
4996  ilUtil::deliverData($result, ilUtil::getASCIIFilename($this->getTitle()) . ".pdf", "application/pdf");
4997  */
4998  }
4999 
5000  function _checkCondition($a_svy_id,$a_operator,$a_value,$a_usr_id = 0)
5001  {
5002  global $ilUser;
5003 
5004  $a_usr_id = $a_usr_id ? $a_usr_id : $ilUser->getId();
5005 
5006  switch($a_operator)
5007  {
5008  case 'finished':
5009  //if (ilExerciseMembers::_lookupStatus($a_exc_id, $ilias->account->getId()) == "passed")
5010  include_once("./Modules/Survey/classes/class.ilObjSurveyAccess.php");
5011  if (ilObjSurveyAccess::_lookupFinished($a_svy_id, $a_usr_id))
5012  {
5013  return true;
5014  }
5015  else
5016  {
5017  return false;
5018  }
5019  break;
5020 
5021  default:
5022  return true;
5023  }
5024  return true;
5025  }
5026 
5033  function isPluginActive($a_pname)
5034  {
5035  global $ilPluginAdmin;
5036  if ($ilPluginAdmin->isActive(IL_COMP_MODULE, "SurveyQuestionPool", "svyq", $a_pname))
5037  {
5038  return TRUE;
5039  }
5040  else
5041  {
5042  return FALSE;
5043  }
5044  }
5045 
5051  public function setSurveyId($survey_id)
5052  {
5053  $this->survey_id = $survey_id;
5054  }
5055 
5062  public function &getUserData($ids)
5063  {
5064  global $ilDB;
5065 
5066  if (!is_array($ids) || count($ids) ==0) return array();
5067 
5068  $result = $ilDB->query("SELECT usr_id, login, lastname, firstname FROM usr_data WHERE " . $ilDB->in('usr_id', $ids, false, 'integer') . " ORDER BY login");
5069  $result_array = array();
5070  while ($row = $ilDB->fetchAssoc($result))
5071  {
5072  $result_array[$row["usr_id"]]= $row;
5073  }
5074  return $result_array;
5075  }
5076 
5077  function &getGroupData($ids)
5078  {
5079  if (!is_array($ids) || count($ids) ==0) return array();
5080  $result = array();
5081  foreach ($ids as $ref_id)
5082  {
5083  $obj_id = ilObject::_lookupObjId($ref_id);
5084  $result[$ref_id] = array("ref_id" => $ref_id, "title" => ilObject::_lookupTitle($obj_id), "description" => ilObject::_lookupDescription($obj_id));
5085  }
5086  return $result;
5087  }
5088 
5089  function &getRoleData($ids)
5090  {
5091  if (!is_array($ids) || count($ids) ==0) return array();
5092  $result = array();
5093  foreach ($ids as $obj_id)
5094  {
5095  $result[$obj_id] = array("obj_id" => $obj_id, "title" => ilObject::_lookupTitle($obj_id), "description" => ilObject::_lookupDescription($obj_id));
5096  }
5097  return $result;
5098  }
5099 
5101  {
5102  return $this->mailnotification;
5103  }
5104 
5105  function setMailNotification($a_notification)
5106  {
5107  $this->mailnotification = ($a_notification) ? true : false;
5108  }
5109 
5110  function getMailAddresses()
5111  {
5112  return $this->mailaddresses;
5113  }
5114 
5115  function setMailAddresses($a_addresses)
5116  {
5117  $this->mailaddresses = $a_addresses;
5118  }
5119 
5121  {
5123  }
5124 
5125  function setMailParticipantData($a_data)
5126  {
5127  $this->mailparticipantdata = $a_data;
5128  }
5129 
5130  public function getSurveyTimes()
5131  {
5132  global $ilDB;
5133 
5134  $result = $ilDB->queryF("SELECT * FROM svy_times, svy_finished WHERE svy_finished.survey_fi = %s",
5135  array('integer'),
5136  array($this->getId())
5137  );
5138  $times = array();;
5139  while ($row = $ilDB->fetchAssoc($result))
5140  {
5141  if (strlen($row['left_page']) && strlen($row['entered_page']))
5142  $times[$row['finished_fi']] += ($row['left_page']-$row['entered_page']);
5143  }
5144  return $times;
5145  }
5146 
5147  function setStartTime($finished_id, $first_question)
5148  {
5149  global $ilDB;
5150  $time = time();
5151  $_SESSION['svy_entered_page'] = $time;
5152  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_times (finished_fi, entered_page, left_page, first_question) VALUES (%s, %s, %s, %s)",
5153  array('integer', 'integer', 'integer', 'integer'),
5154  array($finished_id, $time, NULL, $first_question)
5155  );
5156  }
5157 
5158  function setEndTime($finished_id)
5159  {
5160  global $ilDB;
5161  $time = time();
5162  $affectedRows = $ilDB->manipulateF("UPDATE svy_times SET left_page = %s WHERE finished_fi = %s AND entered_page = %s",
5163  array('integer', 'integer', 'integer'),
5164  array($time, $finished_id, $_SESSION['svy_entered_page'])
5165  );
5166  unset($_SESSION['svy_entered_page']);
5167  }
5168 
5169  function getWorkingtimeForParticipant($finished_id)
5170  {
5171  global $ilDB;
5172 
5173  $result = $ilDB->queryF("SELECT * FROM svy_times WHERE finished_fi = %s",
5174  array('integer'),
5175  array($finished_id)
5176  );
5177  $total = 0;
5178  while ($row = $ilDB->fetchAssoc($result))
5179  {
5180  if ($row['left_page'] > 0 && $row['entered_page'] > 0)
5181  $total += $row['left_page'] - $row['entered_page'];
5182  }
5183  return $total;
5184  }
5185 
5186 } // END class.ilObjSurvey
5187 ?>