ILIAS  release_4-3 Revision
 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 "./Services/Object/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 
95  var $end_date;
96 
103 
110 
117 
123 
129 
136 
142 
146 
153  function ilObjSurvey($a_id = 0,$a_call_by_reference = true)
154  {
155  global $ilUser;
156  $this->type = "svy";
157  $this->ilObject($a_id,$a_call_by_reference);
158 
159  $this->survey_id = -1;
160  $this->introduction = "";
161  $this->outro = $this->lng->txt("survey_finished");
162  $this->author = $ilUser->fullname;
163  $this->status = STATUS_OFFLINE;
164  $this->evaluation_access = EVALUATION_ACCESS_OFF;
165  $this->questions = array();
166  $this->invitation = INVITATION_OFF;
167  $this->invitation_mode = MODE_PREDEFINED_USERS;
168  $this->anonymize = ANONYMIZE_OFF;
169  $this->display_question_titles = QUESTIONTITLES_VISIBLE;
170  $this->surveyCodeSecurity = TRUE;
171  $this->template_id = NULL;
172  $this->pool_usage = true;
173  }
174 
178  function create($a_upload = false)
179  {
180  parent::create();
181  if(!$a_upload)
182  {
183  $this->createMetaData();
184  }
185  }
186 
192  function createMetaData()
193  {
195  $this->saveAuthorToMetadata();
196  }
197 
204  function update()
205  {
206  $this->updateMetaData();
207 
208  if (!parent::update())
209  {
210  return false;
211  }
212 
213  // put here object specific stuff
214 
215  return true;
216  }
217 
218  function createReference()
219  {
221  $this->saveToDb();
222  return $result;
223  }
224 
230  function read($a_force_db = false)
231  {
232  parent::read($a_force_db);
233  $this->loadFromDb();
234  }
235 
242  function addQuestion($question_id)
243  {
244  array_push($this->questions, $question_id);
245  }
246 
247 
254  function delete()
255  {
256  $remove = parent::delete();
257  // always call parent delete function first!!
258  if (!$remove)
259  {
260  return false;
261  }
262 
263  $this->deleteMetaData();
264 
265  // Delete all survey questions, constraints and materials
266  foreach ($this->questions as $question_id)
267  {
268  $this->removeQuestion($question_id);
269  }
270  $this->deleteSurveyRecord();
271 
273  return true;
274  }
275 
282  {
283  global $ilDB;
284 
285  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_svy WHERE survey_id = %s",
286  array('integer'),
287  array($this->getSurveyId())
288  );
289 
290  $result = $ilDB->queryF("SELECT questionblock_fi FROM svy_qblk_qst WHERE survey_fi = %s",
291  array('integer'),
292  array($this->getSurveyId())
293  );
294  $questionblocks = array();
295  while ($row = $ilDB->fetchAssoc($result))
296  {
297  array_push($questionblocks, $row["questionblock_fi"]);
298  }
299  if (count($questionblocks))
300  {
301  $affectedRows = $ilDB->manipulate("DELETE FROM svy_qblk WHERE " . $ilDB->in('questionblock_id', $questionblocks, false, 'integer'));
302  }
303  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE survey_fi = %s",
304  array('integer'),
305  array($this->getSurveyId())
306  );
307  $this->deleteAllUserData();
308 
309  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_anonymous WHERE survey_fi = %s",
310  array('integer'),
311  array($this->getSurveyId())
312  );
313 
314  // delete export files
315  include_once "./Services/Utilities/classes/class.ilUtil.php";
316  $svy_data_dir = ilUtil::getDataDir()."/svy_data";
317  $directory = $svy_data_dir."/svy_".$this->getId();
318  if (is_dir($directory))
319  {
320  include_once "./Services/Utilities/classes/class.ilUtil.php";
321  ilUtil::delDir($directory);
322  }
323 
324  include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php");
325  $mobs = ilObjMediaObject::_getMobsOfObject("svy:html", $this->getId());
326  // remaining usages are not in text anymore -> delete them
327  // and media objects (note: delete method of ilObjMediaObject
328  // checks whether object is used in another context; if yes,
329  // the object is not deleted!)
330  foreach($mobs as $mob)
331  {
332  ilObjMediaObject::_removeUsage($mob, "svy:html", $this->getId());
333  $mob_obj =& new ilObjMediaObject($mob);
334  $mob_obj->delete();
335  }
336  }
337 
343  function deleteAllUserData()
344  {
345  global $ilDB;
346 
347  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
348  array('integer'),
349  array($this->getSurveyId())
350  );
351  $active_array = array();
352  while ($row = $ilDB->fetchAssoc($result))
353  {
354  array_push($active_array, $row["finished_id"]);
355  }
356 
357  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_finished WHERE survey_fi = %s",
358  array('integer'),
359  array($this->getSurveyId())
360  );
361 
362  foreach ($active_array as $active_fi)
363  {
364  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE active_fi = %s",
365  array('integer'),
366  array($active_fi)
367  );
368  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_times WHERE finished_fi = %s",
369  array('integer'),
370  array($active_fi)
371  );
372  }
373  }
374 
380  function removeSelectedSurveyResults($finished_ids)
381  {
382  global $ilDB;
383 
384  foreach ($finished_ids as $finished_id)
385  {
386  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE finished_id = %s",
387  array('integer'),
388  array($finished_id)
389  );
390  $row = $ilDB->fetchAssoc($result);
391 
392  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE active_fi = %s",
393  array('integer'),
394  array($row["finished_id"])
395  );
396 
397  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_finished WHERE finished_id = %s",
398  array('integer'),
399  array($finished_id)
400  );
401 
402  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_times WHERE finished_fi = %s",
403  array('integer'),
404  array($row["finished_id"])
405  );
406  }
407  }
408 
410  {
411  global $ilDB;
412 
413  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s",
414  array('integer'),
415  array($this->getSurveyId())
416  );
417  $participants = array();
418  if ($result->numRows() > 0)
419  {
420  while ($row = $ilDB->fetchAssoc($result))
421  {
422  $userdata = $this->getUserDataFromActiveId($row["finished_id"]);
423  $participants[$userdata["sortname"] . $userdata["active_id"]] = $userdata;
424  }
425  }
426  return $participants;
427  }
428 
442  function notify($a_event,$a_ref_id,$a_parent_non_rbac_id,$a_node_id,$a_params = 0)
443  {
444  global $tree;
445 
446  switch ($a_event)
447  {
448  case "link":
449 
450  //var_dump("<pre>",$a_params,"</pre>");
451  //echo "Module name ".$this->getRefId()." triggered by link event. Objects linked into target object ref_id: ".$a_ref_id;
452  //exit;
453  break;
454 
455  case "cut":
456 
457  //echo "Module name ".$this->getRefId()." triggered by cut event. Objects are removed from target object ref_id: ".$a_ref_id;
458  //exit;
459  break;
460 
461  case "copy":
462 
463  //var_dump("<pre>",$a_params,"</pre>");
464  //echo "Module name ".$this->getRefId()." triggered by copy event. Objects are copied into target object ref_id: ".$a_ref_id;
465  //exit;
466  break;
467 
468  case "paste":
469 
470  //echo "Module name ".$this->getRefId()." triggered by paste (cut) event. Objects are pasted into target object ref_id: ".$a_ref_id;
471  //exit;
472  break;
473 
474  case "new":
475 
476  //echo "Module name ".$this->getRefId()." triggered by paste (new) event. Objects are applied to target object ref_id: ".$a_ref_id;
477  //exit;
478  break;
479  }
480 
481  // At the beginning of the recursive process it avoids second call of the notify function with the same parameter
482  if ($a_node_id==$_GET["ref_id"])
483  {
484  $parent_obj =& $this->ilias->obj_factory->getInstanceByRefId($a_node_id);
485  $parent_type = $parent_obj->getType();
486  if($parent_type == $this->getType())
487  {
488  $a_node_id = (int) $tree->getParentId($a_node_id);
489  }
490  }
491 
492  parent::notify($a_event,$a_ref_id,$a_parent_non_rbac_id,$a_node_id,$a_params);
493  }
494 
501  function isComplete()
502  {
503  if (($this->getTitle()) and (count($this->questions)))
504  {
505  return 1;
506  }
507  else
508  {
509  return 0;
510  }
511  }
512 
519  function _isComplete($obj_id)
520  {
521  $survey = new ilObjSurvey($obj_id, false);
522  $survey->loadFromDb();
523  if (($survey->getTitle()) and (count($survey->questions)))
524  {
525  return 1;
526  }
527  else
528  {
529  return 0;
530  }
531  }
532 
539  function &_getGlobalSurveyData($obj_id)
540  {
541  $survey = new ilObjSurvey($obj_id, false);
542  $survey->loadFromDb();
543  $result = array();
544  if (($survey->getTitle()) and ($survey->author) and (count($survey->questions)))
545  {
546  $result["complete"] = true;
547  }
548  else
549  {
550  $result["complete"] = false;
551  }
552  $result["evaluation_access"] = $survey->getEvaluationAccess();
553  return $result;
554  }
555 
562  {
563  global $ilDB;
564 
565  $complete = 0;
566  if ($this->isComplete())
567  {
568  $complete = 1;
569  }
570  if ($this->getSurveyId() > 0)
571  {
572  $affectedRows = $ilDB->manipulateF("UPDATE svy_svy SET complete = %s, tstamp = %s WHERE survey_id = %s",
573  array('text','integer','integer'),
574  array($this->isComplete(), time(), $this->getSurveyId())
575  );
576  }
577  }
578 
586  function duplicateQuestionForSurvey($question_id, $a_force = false)
587  {
588  global $ilUser;
589 
590  $questiontype = $this->getQuestionType($question_id);
591  $question_gui = $this->getQuestionGUI($questiontype, $question_id);
592 
593  // check if question is a pool question at all, if not do nothing
594  if($this->getId() == $question_gui->object->getObjId() && !$a_force)
595  {
596  return $question_id;
597  }
598 
599  $duplicate_id = $question_gui->object->duplicate(true);
600  return $duplicate_id;
601  }
602 
608  function insertQuestion($question_id)
609  {
610  global $ilDB;
611 
612  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
613  if (!SurveyQuestion::_isComplete($question_id))
614  {
615  return FALSE;
616  }
617  else
618  {
619  // get maximum sequence index in test
620  $result = $ilDB->queryF("SELECT survey_question_id FROM svy_svy_qst WHERE survey_fi = %s",
621  array('integer'),
622  array($this->getSurveyId())
623  );
624  $sequence = $result->numRows();
625  $duplicate_id = $this->duplicateQuestionForSurvey($question_id);
626  $next_id = $ilDB->nextId('svy_svy_qst');
627  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_svy_qst (survey_question_id, survey_fi, question_fi, sequence, tstamp) VALUES (%s, %s, %s, %s, %s)",
628  array('integer', 'integer', 'integer', 'integer', 'integer'),
629  array($next_id, $this->getSurveyId(), $duplicate_id, $sequence, time())
630  );
631  $this->loadQuestionsFromDb();
632  return TRUE;
633  }
634  }
635 
636 
642  function insertQuestionblock($questionblock_id)
643  {
644  global $ilDB;
645  $result = $ilDB->queryF("SELECT svy_qblk.title, svy_qblk.show_questiontext, svy_qblk.show_blocktitle,".
646  " svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst, svy_svy_qst".
647  " WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi".
648  " AND svy_svy_qst.question_fi = svy_qblk_qst.question_fi".
649  " AND svy_qblk.questionblock_id = %s".
650  " ORDER BY svy_svy_qst.sequence",
651  array('integer'),
652  array($questionblock_id)
653  );
654  $questions = array();
655  $show_questiontext = 0;
656  $show_blocktitle = 0;
657  while ($row = $ilDB->fetchAssoc($result))
658  {
659  $duplicate_id = $this->duplicateQuestionForSurvey($row["question_fi"]);
660  array_push($questions, $duplicate_id);
661  $title = $row["title"];
662  $show_questiontext = $row["show_questiontext"];
663  $show_blocktitle = $row["show_blocktitle"];
664  }
665  $this->createQuestionblock($title, $show_questiontext, $show_blocktitle, $questions);
666  }
667 
673  function getAllRTEContent()
674  {
675  $result = array();
676  array_push($result, $this->getIntroduction());
677  array_push($result, $this->getOutro());
678  return $result;
679  }
680 
687  {
688  include_once("./Services/RTE/classes/class.ilRTE.php");
689  $completecontent = "";
690  foreach ($this->getAllRTEContent() as $content)
691  {
692  $completecontent .= $content;
693  }
694  ilRTE::_cleanupMediaObjectUsage($completecontent, $this->getType() . ":html",
695  $this->getId());
696  }
697 
698  public function saveUserSettings($usr_id, $key, $title, $value)
699  {
700  global $ilDB;
701 
702  $next_id = $ilDB->nextId('svy_settings');
703  $affectedRows = $ilDB->insert("svy_settings", array(
704  "settings_id" => array("integer", $next_id),
705  "usr_id" => array("integer", $usr_id),
706  "keyword" => array("text", $key),
707  "title" => array("text", $title),
708  "value" => array("clob", $value)
709  ));
710  }
711 
712  public function deleteUserSettings($id)
713  {
714  global $ilDB;
715 
716  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_settings WHERE settings_id = %s",
717  array('integer'),
718  array($id)
719  );
720  return $affectedRows;
721  }
722 
723  public function getUserSettings($usr_id, $key)
724  {
725  global $ilDB;
726 
727  $result = $ilDB->queryF("SELECT * FROM svy_settings WHERE usr_id = %s AND keyword = %s",
728  array('integer', 'text'),
729  array($usr_id, $key)
730  );
731  $found = array();
732  if ($result->numRows())
733  {
734  while ($row = $ilDB->fetchAssoc($result))
735  {
736  $found[$row['settings_id']] = $row;
737  }
738  }
739  return $found;
740  }
741 
747  function saveToDb()
748  {
749  global $ilDB;
750 
751  include_once("./Services/RTE/classes/class.ilRTE.php");
752  if ($this->getSurveyId() < 1)
753  {
754  $next_id = $ilDB->nextId('svy_svy');
755  $affectedRows = $ilDB->insert("svy_svy", array(
756  "survey_id" => array("integer", $next_id),
757  "obj_fi" => array("integer", $this->getId()),
758  "author" => array("text", $this->getAuthor()),
759  "introduction" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getIntroduction(), 0)),
760  "outro" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getOutro(), 0)),
761  "status" => array("text", $this->getStatus()),
762  "startdate" => array("text", $this->getStartDate()),
763  "enddate" => array("text", $this->getEndDate()),
764  "evaluation_access" => array("text", $this->getEvaluationAccess()),
765  "invitation" => array("text", $this->getInvitation()),
766  "invitation_mode" => array("text", $this->getInvitationMode()),
767  "complete" => array("text", $this->isComplete()),
768  "created" => array("integer", time()),
769  "anonymize" => array("text", $this->getAnonymize()),
770  "show_question_titles" => array("text", $this->getShowQuestionTitles()),
771  "mailnotification" => array('integer', ($this->getMailNotification()) ? 1 : 0),
772  "mailaddresses" => array('text', strlen($this->getMailAddresses()) ? $this->getMailAddresses() : NULL),
773  "mailparticipantdata" => array('text', strlen($this->getMailParticipantData()) ? $this->getMailParticipantData() : NULL),
774  "tstamp" => array("integer", time()),
775  "template_id" => array("integer", $this->getTemplate()),
776  "pool_usage" => array("integer", $this->getPoolUsage())
777  ));
778  $this->setSurveyId($next_id);
779  }
780  else
781  {
782  $affectedRows = $ilDB->update("svy_svy", array(
783  "author" => array("text", $this->getAuthor()),
784  "introduction" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getIntroduction(), 0)),
785  "outro" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getOutro(), 0)),
786  "status" => array("text", $this->getStatus()),
787  "startdate" => array("text", $this->getStartDate()),
788  "enddate" => array("text", $this->getEndDate()),
789  "evaluation_access" => array("text", $this->getEvaluationAccess()),
790  "invitation" => array("text", $this->getInvitation()),
791  "invitation_mode" => array("text", $this->getInvitationMode()),
792  "complete" => array("text", $this->isComplete()),
793  "anonymize" => array("text", $this->getAnonymize()),
794  "show_question_titles" => array("text", $this->getShowQuestionTitles()),
795  "mailnotification" => array('integer', ($this->getMailNotification()) ? 1 : 0),
796  "mailaddresses" => array('text', strlen($this->getMailAddresses()) ? $this->getMailAddresses() : NULL),
797  "mailparticipantdata" => array('text', strlen($this->getMailParticipantData()) ? $this->getMailParticipantData() : NULL),
798  "tstamp" => array("integer", time()),
799  "template_id" => array("integer", $this->getTemplate()),
800  "pool_usage" => array("integer", $this->getPoolUsage())
801  ), array(
802  "survey_id" => array("integer", $this->getSurveyId())
803  ));
804  }
805  if ($affectedRows)
806  {
807  // save questions to db
808  $this->saveQuestionsToDb();
809  }
810 
811  // moved activation to ilObjectActivation
812  if($this->ref_id)
813  {
814  include_once "./Services/Object/classes/class.ilObjectActivation.php";
815  ilObjectActivation::getItem($this->ref_id);
816 
817  $item = new ilObjectActivation;
818  if(!$this->isActivationLimited())
819  {
821  }
822  else
823  {
824  $item->setTimingType(ilObjectActivation::TIMINGS_ACTIVATION);
825  $item->setTimingStart($this->getActivationStartDate());
826  $item->setTimingEnd($this->getActivationEndDate());
827  $item->toggleVisible($this->getActivationVisibility());
828  }
829 
830  $item->update($this->ref_id);
831  }
832  }
833 
840  function saveQuestionsToDb()
841  {
842  global $ilDB;
843  // save old questions state
844  $old_questions = array();
845  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE survey_fi = %s",
846  array('integer'),
847  array($this->getSurveyId())
848  );
849  if ($result->numRows())
850  {
851  while ($row = $ilDB->fetchAssoc($result))
852  {
853  $old_questions[$row["question_fi"]] = $row;
854  }
855  }
856 
857  // delete existing question relations
858  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_svy_qst WHERE survey_fi = %s",
859  array('integer'),
860  array($this->getSurveyId())
861  );
862  // create new question relations
863  foreach ($this->questions as $key => $value)
864  {
865  $next_id = $ilDB->nextId('svy_svy_qst');
866  $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)",
867  array('integer','integer','integer','text','integer','integer'),
868  array($next_id, $this->getSurveyId(), $value, (strlen($old_questions[$value]["heading"])) ? $old_questions[$value]["heading"] : NULL, $key, time())
869  );
870  }
871  }
872 
880  function getAnonymousId($id)
881  {
882  global $ilDB;
883  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_finished WHERE anonymous_id = %s",
884  array('text'),
885  array($id)
886  );
887  if ($result->numRows())
888  {
889  $row = $ilDB->fetchAssoc($result);
890  return $row["anonymous_id"];
891  }
892  else
893  {
894  return "";
895  }
896  }
897 
904  function getQuestionGUI($questiontype, $question_id)
905  {
906  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestionGUI.php";
907  return SurveyQuestionGUI::_getQuestionGUI($questiontype, $question_id);
908  }
909 
917  function getQuestionType($question_id)
918  {
919  global $ilDB;
920  if ($question_id < 1) return -1;
921  $result = $ilDB->queryF("SELECT type_tag FROM svy_question, svy_qtype WHERE svy_question.question_id = %s AND " .
922  "svy_question.questiontype_fi = svy_qtype.questiontype_id",
923  array('integer'),
924  array($question_id)
925  );
926  if ($result->numRows() == 1)
927  {
928  $data = $ilDB->fetchAssoc($result);
929  return $data["type_tag"];
930  }
931  else
932  {
933  return "";
934  }
935  }
936 
943  function getSurveyId()
944  {
945  return $this->survey_id;
946  }
947 
951  function setAnonymize($a_anonymize)
952  {
953  switch ($a_anonymize)
954  {
955  case ANONYMIZE_OFF:
956  case ANONYMIZE_ON:
958  case ANONYMIZE_CODE_ALL:
959  $this->anonymize = $a_anonymize;
960  break;
961  default:
962  $this->anonymize = ANONYMIZE_OFF;
963  break;
964  }
965  }
966 
972  function getAnonymize()
973  {
974  return ($this->anonymize) ? $this->anonymize : 0;
975  }
976 
978  {
979  if ($this->getAnonymize() == ANONYMIZE_CODE_ALL)
980  {
981  return true;
982  }
983  else
984  {
985  return false;
986  }
987  }
988 
995  {
996  if ($this->getAnonymize() == ANONYMIZE_FREEACCESS)
997  {
998  return true;
999  }
1000  else
1001  {
1002  return false;
1003  }
1004  }
1005 
1011  function loadFromDb()
1012  {
1013  global $ilDB;
1014  $result = $ilDB->queryF("SELECT * FROM svy_svy WHERE obj_fi = %s",
1015  array('integer'),
1016  array($this->getId())
1017  );
1018  if ($result->numRows() == 1)
1019  {
1020  $data = $ilDB->fetchAssoc($result);
1021  $this->setSurveyId($data["survey_id"]);
1022  $this->setAuthor($data["author"]);
1023  include_once("./Services/RTE/classes/class.ilRTE.php");
1024  $this->setIntroduction(ilRTE::_replaceMediaObjectImageSrc($data["introduction"], 1));
1025  if (strcmp($data["outro"], "survey_finished") == 0)
1026  {
1027  $this->setOutro($this->lng->txt("survey_finished"));
1028  }
1029  else
1030  {
1031  $this->setOutro(ilRTE::_replaceMediaObjectImageSrc($data["outro"], 1));
1032  }
1033  $this->setInvitation($data["invitation"]);
1034  $this->setInvitationMode($data["invitation_mode"]);
1035  $this->setShowQuestionTitles($data["show_question_titles"]);
1036  $this->setStartDate($data["startdate"]);
1037  $this->setEndDate($data["enddate"]);
1038  $this->setAnonymize($data["anonymize"]);
1039  $this->setEvaluationAccess($data["evaluation_access"]);
1040  $this->loadQuestionsFromDb();
1041  $this->setStatus($data["status"]);
1042  $this->setMailNotification($data['mailnotification']);
1043  $this->setMailAddresses($data['mailaddresses']);
1044  $this->setMailParticipantData($data['mailparticipantdata']);
1045  $this->setTemplate($data['template_id']);
1046  $this->setPoolUsage($data['pool_usage']);
1047  }
1048 
1049  // moved activation to ilObjectActivation
1050  if($this->ref_id)
1051  {
1052  include_once "./Services/Object/classes/class.ilObjectActivation.php";
1053  $activation = ilObjectActivation::getItem($this->ref_id);
1054  switch($activation["timing_type"])
1055  {
1057  $this->setActivationLimited(true);
1058  $this->setActivationStartDate($activation["timing_start"]);
1059  $this->setActivationEndDate($activation["timing_end"]);
1060  $this->setActivationVisibility($activation["visible"]);
1061  break;
1062 
1063  default:
1064  $this->setActivationLimited(false);
1065  break;
1066  }
1067  }
1068  }
1069 
1077  {
1078  global $ilDB;
1079  $this->questions = array();
1080  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE survey_fi = %s ORDER BY sequence",
1081  array('integer'),
1082  array($this->getSurveyId())
1083  );
1084  while ($data = $ilDB->fetchAssoc($result))
1085  {
1086  $this->questions[$data["sequence"]] = $data["question_fi"];
1087  }
1088  }
1089 
1097  function setAuthor($author = "")
1098  {
1099  $this->author = $author;
1100  }
1101 
1111  function saveAuthorToMetadata($a_author = "")
1112  {
1113  $md =& new ilMD($this->getId(), 0, $this->getType());
1114  $md_life =& $md->getLifecycle();
1115  if (!$md_life)
1116  {
1117  if (strlen($a_author) == 0)
1118  {
1119  global $ilUser;
1120  $a_author = $ilUser->getFullname();
1121  }
1122 
1123  $md_life =& $md->addLifecycle();
1124  $md_life->save();
1125  $con =& $md_life->addContribute();
1126  $con->setRole("Author");
1127  $con->save();
1128  $ent =& $con->addEntity();
1129  $ent->setEntity($a_author);
1130  $ent->save();
1131  }
1132  }
1133 
1141  function getAuthor()
1142  {
1143  $author = array();
1144  include_once "./Services/MetaData/classes/class.ilMD.php";
1145  $md =& new ilMD($this->getId(), 0, $this->getType());
1146  $md_life =& $md->getLifecycle();
1147  if ($md_life)
1148  {
1149  $ids =& $md_life->getContributeIds();
1150  foreach ($ids as $id)
1151  {
1152  $md_cont =& $md_life->getContribute($id);
1153  if (strcmp($md_cont->getRole(), "Author") == 0)
1154  {
1155  $entids =& $md_cont->getEntityIds();
1156  foreach ($entids as $entid)
1157  {
1158  $md_ent =& $md_cont->getEntity($entid);
1159  array_push($author, $md_ent->getEntity());
1160  }
1161  }
1162  }
1163  }
1164  return join($author, ",");
1165  }
1166 
1173  public function getShowQuestionTitles()
1174  {
1175  return ($this->display_question_titles) ? 1 : 0;
1176  }
1177 
1184  public function setShowQuestionTitles($a_show)
1185  {
1186  $this->display_question_titles = ($a_show) ? 1 : 0;
1187  }
1188 
1196  {
1197  $this->display_question_titles = 1;
1198  }
1199 
1207  {
1208  $this->display_question_titles = 0;
1209  }
1210 
1219  {
1220  global $ilDB;
1221  global $ilAccess;
1222  $this->invitation = $invitation;
1223  if ($invitation == INVITATION_OFF)
1224  {
1225  $this->disinviteAllUsers();
1226  }
1227  else if ($invitation == INVITATION_ON)
1228  {
1229  if ($this->getInvitationMode() == MODE_UNLIMITED)
1230  {
1231  $result = $ilDB->query("SELECT usr_id FROM usr_data");
1232  while ($row = $ilDB->fetchAssoc($result))
1233  {
1234  if ($ilAccess->checkAccessOfUser($row["usr_id"], "read", "", $this->getRefId(), "svy", $this->getId()))
1235  {
1236  $this->inviteUser($row['usr_id']);
1237  }
1238  }
1239  }
1240  }
1241  }
1242 
1251  {
1252  $this->invitation_mode = $invitation_mode;
1253  }
1254 
1264  {
1265  $this->invitation_mode = $invitation_mode;
1266  $this->setInvitation($invitation);
1267  }
1268 
1275  public function setIntroduction($introduction = "")
1276  {
1277  $this->introduction = $introduction;
1278  }
1279 
1286  public function setOutro($outro = "")
1287  {
1288  $this->outro = $outro;
1289  }
1290 
1298  function getInvitation()
1299  {
1300  return ($this->invitation) ? $this->invitation : INVITATION_OFF;
1301  }
1302 
1310  function getInvitationMode()
1311  {
1312  include_once "./Services/Administration/classes/class.ilSetting.php";
1313  $surveySetting = new ilSetting("survey");
1314  $unlimited_invitation = $surveySetting->get("unlimited_invitation");
1315  if (!$unlimited_invitation && $this->invitation_mode == MODE_UNLIMITED)
1316  {
1317  return MODE_PREDEFINED_USERS;
1318  }
1319  else
1320  {
1321  return ($this->invitation_mode) ? $this->invitation_mode : MODE_UNLIMITED;
1322  }
1323  }
1324 
1332  function getStatus()
1333  {
1334  return ($this->status) ? $this->status : STATUS_OFFLINE;
1335  }
1336 
1344  function isOnline()
1345  {
1346  return ($this->status == STATUS_ONLINE) ? true : false;
1347  }
1348 
1356  function isOffline()
1357  {
1358  return ($this->status == STATUS_OFFLINE) ? true : false;
1359  }
1360 
1370  {
1371  $result = "";
1372  if (($status == STATUS_ONLINE) && (count($this->questions) == 0))
1373  {
1374  $this->status = STATUS_OFFLINE;
1375  $result = $this->lng->txt("cannot_switch_to_online_no_questions");
1376  }
1377  else
1378  {
1379  $this->status = $status;
1380  }
1381  return $result;
1382  }
1383 
1391  function getStartDate()
1392  {
1393  return (strlen($this->start_date)) ? $this->start_date : NULL;
1394  }
1395 
1402  function canStartSurvey($anonymous_id = NULL)
1403  {
1404  global $ilAccess;
1405 
1406  $result = TRUE;
1407  $messages = array();
1408  $edit_settings = false;
1409  // check start date
1410  if (preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getStartDate(), $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('start_date_not_reached').' ('.
1418  $result = FALSE;
1419  $edit_settings = true;
1420  }
1421  }
1422  // check end date
1423  if (preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getEndDate(), $matches))
1424  {
1425  $epoch_time = mktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1426  $now = mktime();
1427  if ($now > $epoch_time)
1428  {
1429  array_push($messages,$this->lng->txt('end_date_reached').' ('.
1431  $result = FALSE;
1432  $edit_settings = true;
1433  }
1434  }
1435 
1436  // check online status
1437  if ($this->getStatus() == STATUS_OFFLINE)
1438  {
1439  array_push($messages, $this->lng->txt("survey_is_offline"));
1440  $result = FALSE;
1441  $edit_settings = true;
1442  }
1443  // check rbac permissions
1444  if (!$ilAccess->checkAccess("read", "", $this->ref_id))
1445  {
1446  array_push($messages, $this->lng->txt("cannot_participate_survey"));
1447  $result = FALSE;
1448  }
1449  // 2. check previous access
1450  if (!$result["error"])
1451  {
1452  global $ilUser;
1453  $survey_started = $this->isSurveyStarted($ilUser->getId(), $anonymous_id);
1454  if ($survey_started === 1)
1455  {
1456  array_push($messages, $this->lng->txt("already_completed_survey"));
1457  $result = FALSE;
1458  }
1459  }
1460  return array(
1461  "result" => $result,
1462  "messages" => $messages,
1463  "edit_settings" => $edit_settings
1464  );
1465  }
1466 
1474  function setStartDate($start_date = "")
1475  {
1476  $this->start_date = $start_date;
1477  }
1478 
1487  function setStartDateAndTime($start_date = "", $start_time)
1488  {
1489  $y = ''; $m = ''; $d = ''; $h = ''; $i = ''; $s = '';
1490  if (preg_match("/(\d{4})-(\d{2})-(\d{2})/", $start_date, $matches))
1491  {
1492  $y = $matches[1];
1493  $m = $matches[2];
1494  $d = $matches[3];
1495  }
1496  if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $start_time, $matches))
1497  {
1498  $h = $matches[1];
1499  $i = $matches[2];
1500  $s = $matches[3];
1501  }
1502  $this->start_date = sprintf('%04d%02d%02d%02d%02d%02d', $y, $m, $d, $h, $i, $s);
1503  }
1504 
1512  function getEndDate()
1513  {
1514  return (strlen($this->end_date)) ? $this->end_date : NULL;
1515  }
1516 
1524  function setEndDate($end_date = "")
1525  {
1526  $this->end_date = $end_date;
1527  }
1528 
1537  function setEndDateAndTime($end_date = "", $end_time)
1538  {
1539  $y = ''; $m = ''; $d = ''; $h = ''; $i = ''; $s = '';
1540  if (preg_match("/(\d{4})-(\d{2})-(\d{2})/", $end_date, $matches))
1541  {
1542  $y = $matches[1];
1543  $m = $matches[2];
1544  $d = $matches[3];
1545  }
1546  if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $end_time, $matches))
1547  {
1548  $h = $matches[1];
1549  $i = $matches[2];
1550  $s = $matches[3];
1551  }
1552  $this->end_date = sprintf('%04d%02d%02d%02d%02d%02d', $y, $m, $d, $h, $i, $s);
1553  }
1554 
1563  {
1564  return ($this->evaluation_access) ? $this->evaluation_access : EVALUATION_ACCESS_OFF;
1565  }
1566 
1575  {
1576  $this->evaluation_access = ($evaluation_access) ? $evaluation_access : EVALUATION_ACCESS_OFF;
1577  }
1578 
1579  function setActivationVisibility($a_value)
1580  {
1581  $this->activation_visibility = (bool) $a_value;
1582  }
1583 
1585  {
1587  }
1588 
1590  {
1591  return (bool)$this->activation_limited;
1592  }
1593 
1594  function setActivationLimited($a_value)
1595  {
1596  $this->activation_limited = (bool)$a_value;
1597  }
1598 
1606  function getIntroduction()
1607  {
1608  return (strlen($this->introduction)) ? $this->introduction : NULL;
1609  }
1610 
1618  function getOutro()
1619  {
1620  return (strlen($this->outro)) ? $this->outro : NULL;
1621  }
1622 
1630  {
1631  global $ilDB;
1632  $existing_questions = array();
1633  $result = $ilDB->queryF("SELECT svy_question.original_id FROM svy_question, svy_svy_qst WHERE " .
1634  "svy_svy_qst.survey_fi = %s AND svy_svy_qst.question_fi = svy_question.question_id",
1635  array('integer'),
1636  array($this->getSurveyId())
1637  );
1638  while ($data = $ilDB->fetchAssoc($result))
1639  {
1640  if($data["original_id"])
1641  {
1642  array_push($existing_questions, $data["original_id"]);
1643  }
1644  }
1645  return $existing_questions;
1646  }
1647 
1654  function &getQuestionpoolTitles($could_be_offline = FALSE, $showPath = FALSE)
1655  {
1656  include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php";
1657  return ilObjSurveyQuestionPool::_getAvailableQuestionpools($use_object_id = TRUE, $could_be_offline, $showPath);
1658  }
1659 
1666  function moveUpQuestion($question_id)
1667  {
1668  $move_questions = array($question_id);
1669  $pages =& $this->getSurveyPages();
1670  $pageindex = -1;
1671  foreach ($pages as $idx => $page)
1672  {
1673  if ($page[0]["question_id"] == $question_id)
1674  {
1675  $pageindex = $idx;
1676  }
1677  }
1678  if ($pageindex > 0)
1679  {
1680  $this->moveQuestions($move_questions, $pages[$pageindex-1][0]["question_id"], 0);
1681  }
1682  else
1683  {
1684  // move up a question in a questionblock
1685  $questions = $this->getSurveyQuestions();
1686  $questions = array_keys($questions);
1687  $index = array_search($question_id, $questions);
1688  if (($index !== FALSE) && ($index > 0))
1689  {
1690  $this->moveQuestions($move_questions, $questions[$index-1], 0);
1691  }
1692  }
1693  }
1694 
1700  public function moveDownQuestion($question_id)
1701  {
1702  $move_questions = array($question_id);
1703  $pages =& $this->getSurveyPages();
1704  $pageindex = -1;
1705  foreach ($pages as $idx => $page)
1706  {
1707  if (($page[0]["question_id"] == $question_id) && (strcmp($page[0]["questionblock_id"], "") == 0))
1708  {
1709  $pageindex = $idx;
1710  }
1711  }
1712  if (($pageindex < count($pages)-1) && ($pageindex >= 0))
1713  {
1714  $this->moveQuestions($move_questions, $pages[$pageindex+1][count($pages[$pageindex+1])-1]["question_id"], 1);
1715  }
1716  else
1717  {
1718  // move down a question in a questionblock
1719  $questions = $this->getSurveyQuestions();
1720  $questions = array_keys($questions);
1721  $index = array_search($question_id, $questions);
1722  if (($index !== FALSE) && ($index < count($questions)-1))
1723  {
1724  $this->moveQuestions($move_questions, $questions[$index+1], 1);
1725  }
1726  }
1727  }
1728 
1735  function moveUpQuestionblock($questionblock_id)
1736  {
1737  $pages =& $this->getSurveyPages();
1738  $move_questions = array();
1739  $pageindex = -1;
1740  foreach ($pages as $idx => $page)
1741  {
1742  if ($page[0]["questionblock_id"] == $questionblock_id)
1743  {
1744  foreach ($page as $pageidx => $question)
1745  {
1746  array_push($move_questions, $question["question_id"]);
1747  }
1748  $pageindex = $idx;
1749  }
1750  }
1751  if ($pageindex > 0)
1752  {
1753  $this->moveQuestions($move_questions, $pages[$pageindex-1][0]["question_id"], 0);
1754  }
1755  }
1756 
1763  function moveDownQuestionblock($questionblock_id)
1764  {
1765  $pages =& $this->getSurveyPages();
1766  $move_questions = array();
1767  $pageindex = -1;
1768  foreach ($pages as $idx => $page)
1769  {
1770  if ($page[0]["questionblock_id"] == $questionblock_id)
1771  {
1772  foreach ($page as $pageidx => $question)
1773  {
1774  array_push($move_questions, $question["question_id"]);
1775  }
1776  $pageindex = $idx;
1777  }
1778  }
1779  if ($pageindex < count($pages)-1)
1780  {
1781  $this->moveQuestions($move_questions, $pages[$pageindex+1][count($pages[$pageindex+1])-1]["question_id"], 1);
1782  }
1783  }
1784 
1793  function moveQuestions($move_questions, $target_index, $insert_mode)
1794  {
1795  $array_pos = array_search($target_index, $this->questions);
1796  if ($insert_mode == 0)
1797  {
1798  $part1 = array_slice($this->questions, 0, $array_pos);
1799  $part2 = array_slice($this->questions, $array_pos);
1800  }
1801  else if ($insert_mode == 1)
1802  {
1803  $part1 = array_slice($this->questions, 0, $array_pos + 1);
1804  $part2 = array_slice($this->questions, $array_pos + 1);
1805  }
1806  foreach ($move_questions as $question_id)
1807  {
1808  if (!(array_search($question_id, $part1) === FALSE))
1809  {
1810  unset($part1[array_search($question_id, $part1)]);
1811  }
1812  if (!(array_search($question_id, $part2) === FALSE))
1813  {
1814  unset($part2[array_search($question_id, $part2)]);
1815  }
1816  }
1817  $part1 = array_values($part1);
1818  $part2 = array_values($part2);
1819  $this->questions = array_values(array_merge($part1, $move_questions, $part2));
1820  foreach ($move_questions as $question_id)
1821  {
1822  $constraints = $this->getConstraints($question_id);
1823  foreach ($constraints as $idx => $constraint)
1824  {
1825  foreach ($part2 as $next_question_id)
1826  {
1827  if ($constraint["question"] == $next_question_id)
1828  {
1829  // constraint concerning a question that follows -> delete constraint
1830  $this->deleteConstraint($constraint["id"]);
1831  }
1832  }
1833  }
1834  }
1835  $this->saveQuestionsToDb();
1836  }
1837 
1844  function removeQuestion($question_id)
1845  {
1846  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
1847  $question =& $this->_instanciateQuestion($question_id);
1848  $question->delete($question_id);
1849  $this->removeConstraintsConcerningQuestion($question_id);
1850  }
1851 
1859  {
1860  global $ilDB;
1861  $result = $ilDB->queryF("SELECT constraint_fi FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s",
1862  array('integer','integer'),
1863  array($question_id, $this->getSurveyId())
1864  );
1865  if ($result->numRows() > 0)
1866  {
1867  $remove_constraints = array();
1868  while ($row = $ilDB->fetchAssoc($result))
1869  {
1870  array_push($remove_constraints, $row["constraint_fi"]);
1871  }
1872  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s",
1873  array('integer','integer'),
1874  array($question_id, $this->getSurveyId())
1875  );
1876  foreach ($remove_constraints as $key => $constraint_id)
1877  {
1878  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_constraint WHERE constraint_id = %s",
1879  array('integer'),
1880  array($constraint_id)
1881  );
1882  }
1883  }
1884  }
1885 
1893  function removeQuestions($remove_questions, $remove_questionblocks)
1894  {
1895  global $ilDB;
1896 
1897  $block_sizes = array();
1898  foreach ($this->getSurveyQuestions() as $question_id => $data)
1899  {
1900  if (in_array($question_id, $remove_questions) or in_array($data["questionblock_id"], $remove_questionblocks))
1901  {
1902  unset($this->questions[array_search($question_id, $this->questions)]);
1903  $this->removeQuestion($question_id);
1904  }
1905  else if($data["questionblock_id"])
1906  {
1907  $block_sizes[$data["questionblock_id"]]++;
1908  }
1909  }
1910 
1911  // blocks with just 1 question need to be deleted
1912  foreach($block_sizes as $block_id => $size)
1913  {
1914  if($size < 2)
1915  {
1916  $remove_questionblocks[] = $block_id;
1917  }
1918  }
1919 
1920  foreach (array_unique($remove_questionblocks) as $questionblock_id)
1921  {
1922  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk WHERE questionblock_id = %s",
1923  array('integer'),
1924  array($questionblock_id)
1925  );
1926  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s",
1927  array('integer','integer'),
1928  array($questionblock_id, $this->getSurveyId())
1929  );
1930  }
1931 
1932  $this->questions = array_values($this->questions);
1933  $this->saveQuestionsToDb();
1934  }
1935 
1942  function unfoldQuestionblocks($questionblocks)
1943  {
1944  global $ilDB;
1945  foreach ($questionblocks as $index)
1946  {
1947  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk WHERE questionblock_id = %s",
1948  array('integer'),
1949  array($index)
1950  );
1951  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s",
1952  array('integer','integer'),
1953  array($index, $this->getSurveyId())
1954  );
1955  }
1956  }
1957 
1958  function removeQuestionFromBlock($question_id, $questionblock_id)
1959  {
1960  global $ilDB;
1961 
1962  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE questionblock_fi = %s AND survey_fi = %s AND question_fi = %s",
1963  array('integer','integer','integer'),
1964  array($questionblock_id, $this->getSurveyId(), $question_id)
1965  );
1966  }
1967 
1968  function addQuestionToBlock($question_id, $questionblock_id)
1969  {
1970  global $ilDB;
1971 
1972 
1973  $next_id = $ilDB->nextId('svy_qblk_qst');
1974  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, " .
1975  "question_fi) VALUES (%s, %s, %s, %s)",
1976  array('integer','integer','integer','integer'),
1977  array($next_id, $this->getSurveyId(), $questionblock_id, $question_id)
1978  );
1979 
1980  $this->deleteConstraints($question_id); // #13713
1981  }
1982 
1989  function &getQuestionblockQuestions($questionblock_id)
1990  {
1991  global $ilDB;
1992  $titles = array();
1993  $result = $ilDB->queryF("SELECT svy_question.title, svy_qblk_qst.question_fi, svy_qblk_qst.survey_fi FROM ".
1994  "svy_qblk, svy_qblk_qst, svy_question WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND " .
1995  "svy_question.question_id = svy_qblk_qst.question_fi AND svy_qblk.questionblock_id = %s",
1996  array('integer'),
1997  array($questionblock_id)
1998  );
1999  $survey_id = "";
2000  while ($row = $ilDB->fetchAssoc($result))
2001  {
2002  $titles[$row["question_fi"]] = $row["title"];
2003  $survey_id = $row["survey_fi"];
2004  }
2005  $result = $ilDB->queryF("SELECT question_fi, sequence FROM svy_svy_qst WHERE survey_fi = %s ORDER BY sequence",
2006  array('integer'),
2007  array($survey_id)
2008  );
2009  $resultarray = array();
2010  $counter = 1;
2011  while ($row = $ilDB->fetchAssoc($result))
2012  {
2013  if (array_key_exists($row["question_fi"], $titles))
2014  {
2015  $resultarray[$counter++] = $titles[$row["question_fi"]];
2016  }
2017  }
2018  return $resultarray;
2019  }
2020 
2027  function &getQuestionblockQuestionIds($questionblock_id)
2028  {
2029  global $ilDB;
2030  $result = $ilDB->queryF("SELECT question_fi FROM svy_qblk_qst WHERE questionblock_fi = %s",
2031  array("integer"),
2032  array($questionblock_id)
2033  );
2034  $ids = array();
2035  if ($result->numRows())
2036  {
2037  while ($data = $ilDB->fetchAssoc($result))
2038  {
2039  array_push($ids, $data['question_fi']);
2040  }
2041  }
2042  return $ids;
2043  }
2044 
2052  function getQuestionblock($questionblock_id)
2053  {
2054  global $ilDB;
2055  $result = $ilDB->queryF("SELECT * FROM svy_qblk WHERE questionblock_id = %s",
2056  array('integer'),
2057  array($questionblock_id)
2058  );
2059  return $ilDB->fetchAssoc($result);
2060  }
2061 
2069  function _getQuestionblock($questionblock_id)
2070  {
2071  global $ilDB;
2072  $result = $ilDB->queryF("SELECT * FROM svy_qblk WHERE questionblock_id = %s",
2073  array('integer'),
2074  array($questionblock_id)
2075  );
2076  $row = $ilDB->fetchAssoc($result);
2077  return $row;
2078  }
2079 
2088  function _addQuestionblock($title = "", $owner = 0, $show_questiontext = true, $show_blocktitle = false)
2089  {
2090  global $ilDB;
2091  $next_id = $ilDB->nextId('svy_qblk');
2092  $ilDB->manipulateF("INSERT INTO svy_qblk (questionblock_id, title, show_questiontext,".
2093  " show_blocktitle, owner_fi, tstamp) " .
2094  "VALUES (%s, %s, %s, %s, %s, %s)",
2095  array('integer','text','integer','integer','integer','integer'),
2096  array($next_id, $title, $show_questiontext, $show_blocktitle, $owner, time())
2097  );
2098  return $next_id;
2099  }
2100 
2108  function createQuestionblock($title, $show_questiontext, $show_blocktitle, $questions)
2109  {
2110  global $ilDB;
2111 
2112  // if the selected questions are not in a continous selection, move all questions of the
2113  // questionblock at the position of the first selected question
2114  $this->moveQuestions($questions, $questions[0], 0);
2115 
2116  // now save the question block
2117  global $ilUser;
2118  $next_id = $ilDB->nextId('svy_qblk');
2119  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk (questionblock_id, title, show_questiontext,".
2120  " show_blocktitle, owner_fi, tstamp) VALUES (%s, %s, %s, %s, %s, %s)",
2121  array('integer','text','text','text','integer','integer'),
2122  array($next_id, $title, $show_questiontext, $show_blocktitle, $ilUser->getId(), time())
2123  );
2124  if ($affectedRows)
2125  {
2126  $questionblock_id = $next_id;
2127  foreach ($questions as $index)
2128  {
2129  $next_id = $ilDB->nextId('svy_qblk_qst');
2130  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, " .
2131  "question_fi) VALUES (%s, %s, %s, %s)",
2132  array('integer','integer','integer','integer'),
2133  array($next_id, $this->getSurveyId(), $questionblock_id, $index)
2134  );
2135  $this->deleteConstraints($index);
2136  }
2137  }
2138  }
2139 
2147  function modifyQuestionblock($questionblock_id, $title, $show_questiontext, $show_blocktitle)
2148  {
2149  global $ilDB;
2150  $affectedRows = $ilDB->manipulateF("UPDATE svy_qblk SET title = %s, show_questiontext = %s,".
2151  " show_blocktitle = %s WHERE questionblock_id = %s",
2152  array('text','text','text','integer'),
2153  array($title, $show_questiontext, $show_blocktitle, $questionblock_id)
2154  );
2155  }
2156 
2163  function deleteConstraints($question_id)
2164  {
2165  global $ilDB;
2166  $result = $ilDB->queryF("SELECT constraint_fi FROM svy_qst_constraint WHERE question_fi = %s AND survey_fi = %s",
2167  array('integer','integer'),
2168  array($question_id, $this->getSurveyId())
2169  );
2170  $constraints = array();
2171  while ($row = $ilDB->fetchAssoc($result))
2172  {
2173  array_push($constraints, $row["constraint_fi"]);
2174  }
2175  foreach ($constraints as $constraint_id)
2176  {
2177  $this->deleteConstraint($constraint_id);
2178  }
2179  }
2180 
2188  function deleteConstraint($constraint_id)
2189  {
2190  global $ilDB;
2191  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_constraint WHERE constraint_id = %s",
2192  array('integer'),
2193  array($constraint_id)
2194  );
2195  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_constraint WHERE constraint_fi = %s",
2196  array('integer'),
2197  array($constraint_id)
2198  );
2199  }
2200 
2206  public function &getSurveyQuestions($with_answers = false)
2207  {
2208  global $ilDB;
2209  $obligatory_states =& $this->getObligatoryStates();
2210  // get questionblocks
2211  $all_questions = array();
2212  $result = $ilDB->queryF("SELECT svy_qtype.type_tag, svy_qtype.plugin, svy_question.question_id, ".
2213  "svy_svy_qst.heading FROM svy_qtype, svy_question, svy_svy_qst WHERE svy_svy_qst.survey_fi = %s AND " .
2214  "svy_svy_qst.question_fi = svy_question.question_id AND svy_question.questiontype_fi = svy_qtype.questiontype_id " .
2215  "ORDER BY svy_svy_qst.sequence",
2216  array('integer'),
2217  array($this->getSurveyId())
2218  );
2219  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
2220  while ($row = $ilDB->fetchAssoc($result))
2221  {
2222  $add = true;
2223  if ($row["plugin"])
2224  {
2225  if (!$this->isPluginActive($row["type_tag"]))
2226  {
2227  $add = false;
2228  }
2229  }
2230  if ($add)
2231  {
2232  $question =& $this->_instanciateQuestion($row["question_id"]);
2233  $questionrow = $question->_getQuestionDataArray($row["question_id"]);
2234  foreach ($row as $key => $value)
2235  {
2236  $questionrow[$key] = $value;
2237  }
2238  $all_questions[$row["question_id"]] = $questionrow;
2239  $all_questions[$row["question_id"]]["usableForPrecondition"] = $question->usableForPrecondition();
2240  $all_questions[$row["question_id"]]["availableRelations"] = $question->getAvailableRelations();
2241  if (array_key_exists($row["question_id"], $obligatory_states))
2242  {
2243  $all_questions[$row["question_id"]]["obligatory"] = $obligatory_states[$row["question_id"]];
2244  }
2245  }
2246  }
2247  // get all questionblocks
2248  $questionblocks = array();
2249  if (count($all_questions))
2250  {
2251  $result = $ilDB->queryF("SELECT svy_qblk.*, svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst WHERE " .
2252  "svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_qblk_qst.survey_fi = %s " .
2253  "AND " . $ilDB->in('svy_qblk_qst.question_fi', array_keys($all_questions), false, 'integer'),
2254  array('integer'),
2255  array($this->getSurveyId())
2256  );
2257  while ($row = $ilDB->fetchAssoc($result))
2258  {
2259  $questionblocks[$row['question_fi']] = $row;
2260  }
2261  }
2262 
2263  foreach ($all_questions as $question_id => $row)
2264  {
2265  $constraints = $this->getConstraints($question_id);
2266  if (isset($questionblocks[$question_id]))
2267  {
2268  $all_questions[$question_id]["questionblock_title"] = $questionblocks[$question_id]['title'];
2269  $all_questions[$question_id]["questionblock_id"] = $questionblocks[$question_id]['questionblock_id'];
2270  $all_questions[$question_id]["constraints"] = $constraints;
2271  }
2272  else
2273  {
2274  $all_questions[$question_id]["questionblock_title"] = "";
2275  $all_questions[$question_id]["questionblock_id"] = "";
2276  $all_questions[$question_id]["constraints"] = $constraints;
2277  }
2278  if ($with_answers)
2279  {
2280  $answers = array();
2281  $result = $ilDB->queryF("SELECT svy_variable.*, svy_category.title FROM svy_variable, svy_category " .
2282  "WHERE svy_variable.question_fi = %s AND svy_variable.category_fi = svy_category.category_id ".
2283  "ORDER BY sequence ASC",
2284  array('integer'),
2285  array($question_id)
2286  );
2287  if ($result->numRows() > 0)
2288  {
2289  while ($data = $ilDB->fetchAssoc($result))
2290  {
2291  array_push($answers, $data["title"]);
2292  }
2293  }
2294  $all_questions[$question_id]["answers"] = $answers;
2295  }
2296  }
2297  return $all_questions;
2298  }
2299 
2306  function setObligatoryStates($obligatory_questions)
2307  {
2308  global $ilDB;
2309  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE survey_fi = %s",
2310  array('integer'),
2311  array($this->getSurveyId())
2312  );
2313  if ($result->numRows())
2314  {
2315  while ($row = $ilDB->fetchAssoc($result))
2316  {
2317  if (!array_key_exists($row["question_fi"], $obligatory_questions))
2318  {
2319  $obligatory_questions[$row["question_fi"]] = 0;
2320  }
2321  }
2322  }
2323 
2324  // set the obligatory states in the database
2325  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_oblig WHERE survey_fi = %s",
2326  array('integer'),
2327  array($this->getSurveyId())
2328  );
2329 
2330  // set the obligatory states in the database
2331  foreach ($obligatory_questions as $question_fi => $obligatory)
2332  {
2333  $next_id = $ilDB->nextId('svy_qst_oblig');
2334  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qst_oblig (question_obligatory_id, survey_fi, question_fi, " .
2335  "obligatory, tstamp) VALUES (%s, %s, %s, %s, %s)",
2336  array('integer','integer','integer','text','integer'),
2337  array($next_id, $this->getSurveyId(), $question_fi, (strlen($obligatory)) ? $obligatory : 0, time())
2338  );
2339 
2340  // #12420
2341  $ilDB->manipulate("UPDATE svy_question".
2342  " SET obligatory = ".$ilDB->quote($obligatory, "integer").
2343  " WHERE question_id = ".$ilDB->quote($question_fi, "integer"));
2344  }
2345  }
2346 
2354  {
2355  global $ilDB;
2356  $obligatory_states = array();
2357  $result = $ilDB->queryF("SELECT * FROM svy_qst_oblig 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  $obligatory_states[$row["question_fi"]] = $row["obligatory"];
2366  }
2367  }
2368  return $obligatory_states;
2369  }
2370 
2376  function &getSurveyPages()
2377  {
2378  global $ilDB;
2379  $obligatory_states =& $this->getObligatoryStates();
2380  // get questionblocks
2381  $all_questions = array();
2382  $result = $ilDB->queryF("SELECT svy_question.*, svy_qtype.type_tag, svy_svy_qst.heading FROM " .
2383  "svy_question, svy_qtype, svy_svy_qst WHERE svy_svy_qst.survey_fi = %s AND " .
2384  "svy_svy_qst.question_fi = svy_question.question_id AND svy_question.questiontype_fi = svy_qtype.questiontype_id ".
2385  "ORDER BY svy_svy_qst.sequence",
2386  array('integer'),
2387  array($this->getSurveyId())
2388  );
2389  while ($row = $ilDB->fetchAssoc($result))
2390  {
2391  $all_questions[$row["question_id"]] = $row;
2392  }
2393  // get all questionblocks
2394  $questionblocks = array();
2395  if (count($all_questions))
2396  {
2397  $result = $ilDB->queryF("SELECT svy_qblk.*, svy_qblk_qst.question_fi FROM svy_qblk, svy_qblk_qst ".
2398  "WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_qblk_qst.survey_fi = %s ".
2399  "AND " . $ilDB->in('svy_qblk_qst.question_fi', array_keys($all_questions), false, 'integer'),
2400  array('integer'),
2401  array($this->getSurveyId())
2402  );
2403  while ($row = $ilDB->fetchAssoc($result))
2404  {
2405  $questionblocks[$row['question_fi']] = $row;
2406  }
2407  }
2408 
2409  $all_pages = array();
2410  $pageindex = -1;
2411  $currentblock = "";
2412  foreach ($all_questions as $question_id => $row)
2413  {
2414  if (array_key_exists($question_id, $obligatory_states))
2415  {
2416  $all_questions[$question_id]["obligatory"] = $obligatory_states[$question_id];
2417  }
2418  $constraints = array();
2419  if (isset($questionblocks[$question_id]))
2420  {
2421  if (!$currentblock or ($currentblock != $questionblocks[$question_id]['questionblock_id']))
2422  {
2423  $pageindex++;
2424  }
2425  $all_questions[$question_id]['page'] = $pageindex;
2426  $all_questions[$question_id]["questionblock_title"] = $questionblocks[$question_id]['title'];
2427  $all_questions[$question_id]["questionblock_id"] = $questionblocks[$question_id]['questionblock_id'];
2428  $all_questions[$question_id]["questionblock_show_questiontext"] = $questionblocks[$question_id]['show_questiontext'];
2429  $all_questions[$question_id]["questionblock_show_blocktitle"] = $questionblocks[$question_id]['show_blocktitle'];
2430  $currentblock = $questionblocks[$question_id]['questionblock_id'];
2431  $constraints = $this->getConstraints($question_id);
2432  $all_questions[$question_id]["constraints"] = $constraints;
2433  }
2434  else
2435  {
2436  $pageindex++;
2437  $all_questions[$question_id]['page'] = $pageindex;
2438  $all_questions[$question_id]["questionblock_title"] = "";
2439  $all_questions[$question_id]["questionblock_id"] = "";
2440  $all_questions[$question_id]["questionblock_show_questiontext"] = 1;
2441  $all_questions[$question_id]["questionblock_show_blocktitle"] = 1;
2442  $currentblock = "";
2443  $constraints = $this->getConstraints($question_id);
2444  $all_questions[$question_id]["constraints"] = $constraints;
2445  }
2446  if (!isset($all_pages[$pageindex]))
2447  {
2448  $all_pages[$pageindex] = array();
2449  }
2450  array_push($all_pages[$pageindex], $all_questions[$question_id]);
2451  }
2452  // calculate position percentage for every page
2453  $max = count($all_pages);
2454  $counter = 1;
2455  foreach ($all_pages as $index => $block)
2456  {
2457  foreach ($block as $blockindex => $question)
2458  {
2459  $all_pages[$index][$blockindex]["position"] = $counter / $max;
2460  }
2461  $counter++;
2462  }
2463  return $all_pages;
2464  }
2465 
2474  function getNextPage($active_page_question_id, $direction)
2475  {
2476  $foundpage = -1;
2477  $pages =& $this->getSurveyPages();
2478  if (strcmp($active_page_question_id, "") == 0)
2479  {
2480  return $pages[0];
2481  }
2482  foreach ($pages as $key => $question_array)
2483  {
2484  foreach ($question_array as $question)
2485  {
2486  if ($active_page_question_id == $question["question_id"])
2487  {
2488  $foundpage = $key;
2489  }
2490  }
2491  }
2492  if ($foundpage == -1)
2493  {
2494  // error: page not found
2495  }
2496  else
2497  {
2498  $foundpage += $direction;
2499  if ($foundpage < 0)
2500  {
2501  return 0;
2502  }
2503  if ($foundpage >= count($pages))
2504  {
2505  return 1;
2506  }
2507  return $pages[$foundpage];
2508  }
2509  }
2510 
2517  function &getAvailableQuestionpools($use_obj_id = false, $could_be_offline = false, $showPath = FALSE, $permission = "read")
2518  {
2519  include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php";
2520  return ilObjSurveyQuestionPool::_getAvailableQuestionpools($use_obj_id, $could_be_offline, $showPath, $permission);
2521  }
2522 
2529  {
2530  global $ilDB;
2531 
2532  $result_array = array();
2533  $result = $ilDB->queryF("SELECT svy_constraint.*, svy_relation.* FROM svy_qst_constraint, svy_constraint, ".
2534  "svy_relation WHERE svy_constraint.relation_fi = svy_relation.relation_id AND ".
2535  "svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_constraint.constraint_id = %s",
2536  array('integer'),
2537  array($id)
2538  );
2539  $pc = array();
2540  if ($result->numRows())
2541  {
2542  $pc = $ilDB->fetchAssoc($result);
2543  }
2544  return $pc;
2545  }
2546 
2552  function getConstraints($question_id)
2553  {
2554  global $ilDB;
2555 
2556  $result_array = array();
2557  $result = $ilDB->queryF("SELECT svy_constraint.*, svy_relation.* FROM svy_qst_constraint, svy_constraint, svy_relation ".
2558  "WHERE svy_constraint.relation_fi = svy_relation.relation_id AND ".
2559  "svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_qst_constraint.question_fi = %s ".
2560  "AND svy_qst_constraint.survey_fi = %s",
2561  array('integer','integer'),
2562  array($question_id, $this->getSurveyId())
2563  );
2564  while ($row = $ilDB->fetchAssoc($result))
2565  {
2566  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
2567  $question_type = SurveyQuestion::_getQuestionType($row["question_fi"]);
2568  SurveyQuestion::_includeClass($question_type);
2569  $question = new $question_type();
2570  $question->loadFromDb($row["question_fi"]);
2571  $valueoutput = $question->getPreconditionValueOutput($row["value"]);
2572  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));
2573  }
2574  return $result_array;
2575  }
2576 
2583  {
2584  global $ilDB;
2585  $result_array = array();
2586  $result = $ilDB->queryF("SELECT svy_qst_constraint.question_fi as for_question, svy_constraint.*, svy_relation.* ".
2587  "FROM svy_qst_constraint, svy_constraint, svy_relation WHERE svy_constraint.relation_fi = svy_relation.relation_id ".
2588  "AND svy_qst_constraint.constraint_fi = svy_constraint.constraint_id AND svy_qst_constraint.survey_fi = %s",
2589  array('integer'),
2590  array($survey_id)
2591  );
2592  while ($row = $ilDB->fetchAssoc($result))
2593  {
2594  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']));
2595  }
2596  return $result_array;
2597  }
2598 
2599 
2605  function &getVariables($question_id)
2606  {
2607  global $ilDB;
2608 
2609  $result_array = array();
2610  $result = $ilDB->queryF("SELECT svy_variable.*, svy_category.title FROM svy_variable LEFT JOIN ".
2611  "svy_category ON svy_variable.category_fi = svy_category.category_id WHERE svy_variable.question_fi = %s ".
2612  "ORDER BY svy_variable.sequence",
2613  array('integer'),
2614  array($question_id)
2615  );
2616  while ($row = $ilDB->fetchObject($result))
2617  {
2618  $result_array[$row->sequence] = $row;
2619  }
2620  return $result_array;
2621  }
2622 
2631  function addConstraint($if_question_id, $relation, $value, $conjunction)
2632  {
2633  global $ilDB;
2634 
2635  $next_id = $ilDB->nextId('svy_constraint');
2636  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_constraint (constraint_id, question_fi, relation_fi, value, conjunction) VALUES ".
2637  "(%s, %s, %s, %s, %s)",
2638  array('integer','integer','integer','float', 'integer'),
2639  array($next_id, $if_question_id, $relation, $value, $conjunction)
2640  );
2641  if ($affectedRows)
2642  {
2643  return $next_id;
2644  }
2645  else
2646  {
2647  return null;
2648  }
2649  }
2650 
2651 
2658  public function addConstraintToQuestion($to_question_id, $constraint_id)
2659  {
2660  global $ilDB;
2661 
2662  $next_id = $ilDB->nextId('svy_qst_constraint');
2663  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qst_constraint (question_constraint_id, survey_fi, question_fi, ".
2664  "constraint_fi) VALUES (%s, %s, %s, %s)",
2665  array('integer','integer','integer','integer'),
2666  array($next_id, $this->getSurveyId(), $to_question_id, $constraint_id)
2667  );
2668  }
2669 
2680  function updateConstraint($precondition_id, $if_question_id, $relation, $value, $conjunction)
2681  {
2682  global $ilDB;
2683  $affectedRows = $ilDB->manipulateF("UPDATE svy_constraint SET question_fi = %s, relation_fi = %s, value = %s, conjunction = %s ".
2684  "WHERE constraint_id = %s",
2685  array('integer','integer','float','integer','integer'),
2686  array($if_question_id, $relation, $value, $conjunction, $precondition_id)
2687  );
2688  }
2689 
2690  public function updateConjunctionForQuestions($questions, $conjunction)
2691  {
2692  global $ilDB;
2693  foreach ($questions as $question_id)
2694  {
2695  $affectedRows = $ilDB->manipulateF("UPDATE svy_constraint SET conjunction = %s ".
2696  "WHERE constraint_id IN (SELECT constraint_fi FROM svy_qst_constraint WHERE svy_qst_constraint.question_fi = %s)",
2697  array('integer','integer'),
2698  array($conjunction, $question_id)
2699  );
2700  }
2701  }
2702 
2708  function getAllRelations($short_as_key = false)
2709  {
2710  global $ilDB;
2711 
2712  // #7987
2713  $custom_order = array("equal", "not_equal", "less", "less_or_equal", "more", "more_or_equal");
2714  $custom_order = array_flip($custom_order);
2715 
2716  $result_array = array();
2717  $result = $ilDB->query("SELECT * FROM svy_relation");
2718  while ($row = $ilDB->fetchAssoc($result))
2719  {
2720  if ($short_as_key)
2721  {
2722  $result_array[$row["shortname"]] = array("short" => $row["shortname"], "long" => $row["longname"], "id" => $row["relation_id"], "order" => $custom_order[$row["longname"]]);
2723  }
2724  else
2725  {
2726  $result_array[$row["relation_id"]] = array("short" => $row["shortname"], "long" => $row["longname"], "order" => $custom_order[$row["longname"]]);
2727  }
2728  }
2729 
2730  $result_array = ilUtil::sortArray($result_array, "order", "ASC", true, true);
2731  foreach($result_array as $idx => $item)
2732  {
2733  unset($result_array[$idx]["order"]);
2734  }
2735 
2736  return $result_array;
2737  }
2738 
2742  public function disinviteAllUsers()
2743  {
2744  global $ilDB;
2745  $result = $ilDB->queryF("SELECT user_fi FROM svy_inv_usr WHERE survey_fi = %s",
2746  array('integer'),
2747  array($this->getSurveyId())
2748  );
2749  while ($row = $ilDB->fetchAssoc($result))
2750  {
2751  $this->disinviteUser($row['user_fi']);
2752  }
2753  }
2754 
2760  public function disinviteUser($user_id)
2761  {
2762  global $ilDB;
2763 
2764  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_inv_usr WHERE survey_fi = %s AND user_fi = %s",
2765  array('integer','integer'),
2766  array($this->getSurveyId(), $user_id)
2767  );
2768  include_once './Services/User/classes/class.ilObjUser.php';
2769  ilObjUser::_dropDesktopItem($user_id, $this->getRefId(), "svy");
2770  }
2771 
2778  function inviteUser($user_id)
2779  {
2780  global $ilDB;
2781 
2782  $result = $ilDB->queryF("SELECT user_fi FROM svy_inv_usr WHERE user_fi = %s AND survey_fi = %s",
2783  array('integer','integer'),
2784  array($user_id, $this->getSurveyId())
2785  );
2786  if ($result->numRows() < 1)
2787  {
2788  $next_id = $ilDB->nextId('svy_inv_usr');
2789  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_inv_usr (invited_user_id, survey_fi, user_fi, tstamp) " .
2790  "VALUES (%s, %s, %s, %s)",
2791  array('integer','integer','integer','integer'),
2792  array($next_id, $this->getSurveyId(), $user_id, time())
2793  );
2794  }
2795  if ($this->getInvitation() == INVITATION_ON)
2796  {
2797  include_once './Services/User/classes/class.ilObjUser.php';
2798  ilObjUser::_addDesktopItem($user_id, $this->getRefId(), "svy");
2799  }
2800  }
2801 
2808  function inviteGroup($group_id)
2809  {
2810  global $ilAccess;
2811  $invited = 0;
2812  include_once "./Modules/Group/classes/class.ilObjGroup.php";
2813  $group = new ilObjGroup($group_id);
2814  $members = $group->getGroupMemberIds();
2815  foreach ($members as $user_id)
2816  {
2817  if ($ilAccess->checkAccessOfUser($user_id, "read", "", $this->getRefId(), "svy", $this->getId()))
2818  {
2819  $this->inviteUser($user_id);
2820  if ($this->getInvitation() == INVITATION_ON)
2821  {
2822  include_once './Services/User/classes/class.ilObjUser.php';
2823  ilObjUser::_addDesktopItem($user_id, $this->getRefId(), "svy");
2824  }
2825  }
2826  }
2827  return $invited;
2828  }
2829 
2836  function inviteRole($role_id)
2837  {
2838  global $rbacreview;
2839  global $ilAccess;
2840  $invited = 0;
2841  $members = $rbacreview->assignedUsers($role_id);
2842  foreach ($members as $user_id)
2843  {
2844  if ($ilAccess->checkAccessOfUser($user_id, "read", "", $this->getRefId(), "svy", $this->getId()))
2845  {
2846  $this->inviteUser($user_id);
2847  if ($this->getInvitation() == INVITATION_ON)
2848  {
2849  include_once './Services/User/classes/class.ilObjUser.php';
2850  ilObjUser::_addDesktopItem($user_id, $this->getRefId(), "svy");
2851  }
2852  }
2853  }
2854  return $invited;
2855  }
2856 
2863  function &getInvitedUsers()
2864  {
2865  global $ilDB;
2866 
2867  $result_array = array();
2868  $result = $ilDB->queryF("SELECT user_fi FROM svy_inv_usr WHERE survey_fi = %s",
2869  array('integer'),
2870  array($this->getSurveyId())
2871  );
2872  while ($row = $ilDB->fetchAssoc($result))
2873  {
2874  array_push($result_array, $row["user_fi"]);
2875  }
2876  return $result_array;
2877  }
2878 
2886  function deleteWorkingData($question_id, $active_id)
2887  {
2888  global $ilDB;
2889 
2890  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE question_fi = %s AND active_fi = %s",
2891  array('integer','integer'),
2892  array($question_id, $active_id)
2893  );
2894  }
2895 
2904  function loadWorkingData($question_id, $active_id)
2905  {
2906  global $ilDB;
2907  $result_array = array();
2908  $result = $ilDB->queryF("SELECT * FROM svy_answer WHERE question_fi = %s AND active_fi = %s",
2909  array('integer','integer'),
2910  array($question_id, $active_id)
2911  );
2912  if ($result->numRows() >= 1)
2913  {
2914  while ($row = $ilDB->fetchAssoc($result))
2915  {
2916  array_push($result_array, $row);
2917  }
2918  return $result_array;
2919  }
2920  else
2921  {
2922  return $result_array;
2923  }
2924  }
2925 
2932  function fillSurveyForUser($user_id = ANONYMOUS_USER_ID)
2933  {
2934  global $ilDB;
2935  // create an anonymous key
2936  $anonymous_id = $this->createNewAccessCode();
2937  $this->saveUserAccessCode($user_id, $anonymous_id);
2938  // create the survey_finished dataset and set the survey finished already
2939  $active_id = $ilDB->nextId('svy_finished');
2940  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_finished (finished_id, survey_fi, user_fi, anonymous_id, state, tstamp) ".
2941  "VALUES (%s, %s, %s, %s, %s, %s)",
2942  array('integer','integer','integer','text','text','integer'),
2943  array($active_id, $this->getSurveyId(), $user_id, $anonymous_id, 1, time())
2944  );
2945  // fill the questions randomly
2946  $pages =& $this->getSurveyPages();
2947  foreach ($pages as $key => $question_array)
2948  {
2949  foreach ($question_array as $question)
2950  {
2951  // instanciate question
2952  require_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
2953  $question =& SurveyQuestion::_instanciateQuestion($question["question_id"]);
2954  $question->saveRandomData($active_id);
2955  }
2956  }
2957  }
2958 
2965  function startSurvey($user_id, $anonymous_id)
2966  {
2967  global $ilUser;
2968  global $ilDB;
2969 
2970  if ($this->getAnonymize() && (strlen($anonymous_id) == 0)) return;
2971 
2972  if (strcmp($user_id, "") == 0)
2973  {
2974  if ($user_id == ANONYMOUS_USER_ID)
2975  {
2976  $user_id = 0;
2977  }
2978  }
2979  $next_id = $ilDB->nextId('svy_finished');
2980  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_finished (finished_id, survey_fi, user_fi, anonymous_id, state, tstamp) ".
2981  "VALUES (%s, %s, %s, %s, %s, %s)",
2982  array('integer','integer','integer','text','text','integer'),
2983  array($next_id, $this->getSurveyId(), $user_id, $anonymous_id, 0, time())
2984  );
2985  return $next_id;
2986  }
2987 
2994  function finishSurvey($user_id, $anonymize_id)
2995  {
2996  global $ilDB;
2997 
2998  if ($this->getAnonymize())
2999  {
3000  $affectedRows = $ilDB->manipulateF("UPDATE svy_finished SET state = %s, user_fi = %s, tstamp = %s ".
3001  "WHERE survey_fi = %s AND anonymous_id = %s",
3002  array('text','integer','integer','integer','text'),
3003  array(1, $user_id, time(), $this->getSurveyId(), $anonymize_id)
3004  );
3005  }
3006  else
3007  {
3008  $affectedRows = $ilDB->manipulateF("UPDATE svy_finished SET state = %s, tstamp = %s WHERE survey_fi = %s AND user_fi = %s",
3009  array('text','integer','integer','integer'),
3010  array(1, time(), $this->getSurveyId(), $user_id)
3011  );
3012  }
3013  if ($this->getMailNotification())
3014  {
3015  $this->sendNotificationMail($user_id, $anonymize_id);
3016  }
3017  }
3018 
3026  function setPage($finished_id, $page_id)
3027  {
3028  global $ilDB;
3029 
3030  $affectedRows = $ilDB->manipulateF("UPDATE svy_finished SET lastpage = %s WHERE finished_id = %s",
3031  array('integer','integer'),
3032  array(($page_id) ? $page_id : 0, $finished_id)
3033  );
3034  }
3035 
3036  function sendNotificationMail($user_id, $anonymize_id)
3037  {
3038  include_once "./Services/User/classes/class.ilObjUser.php";
3039  include_once "./Services/Mail/classes/class.ilMail.php";
3040 
3041  // #12755
3042  $placeholders = array(
3043  "FIRST_NAME" => "firstname",
3044  "LAST_NAME" => "lastname",
3045  "LOGIN" => "login",
3046  // old style
3047  "firstname" => "firstname"
3048  );
3049 
3050  $mail = new ilMail(ANONYMOUS_USER_ID);
3051  $recipients = preg_split('/,/', $this->mailaddresses);
3052  foreach ($recipients as $recipient)
3053  {
3054  $messagetext = $this->mailparticipantdata;
3055  $data = ilObjUser::_getUserData(array($user_id));
3056  $data = $data[0];
3057  foreach ($placeholders as $key => $mapping)
3058  {
3059  if ($this->getAnonymize())
3060  {
3061  $messagetext = str_replace('[' . $key . ']', '', $messagetext);
3062  }
3063  else
3064  {
3065  $messagetext = str_replace('[' . $key . ']', trim($data[$mapping]), $messagetext);
3066  }
3067  }
3068  $active_id = $this->getActiveID($user_id, $anonymize_id);
3069  $messagetext .= ((strlen($messagetext)) ? "\n\n\n" : '') . $this->lng->txt('results') . "\n\n". $this->getParticipantTextResults($active_id);
3070 
3071  // #11298
3072  include_once "./Services/Link/classes/class.ilLink.php";
3073  $link = ilLink::_getStaticLink($this->getRefId(), "svy");
3074  $messagetext .= "\n\n".$this->lng->txt('obj_svy').": ". $this->getTitle()."\n";
3075  $messagetext .= "\n".$this->lng->txt('survey_notification_tutor_link').": ".$link;
3076  $mail->appendInstallationSignature(true);
3077 
3078  $mail->sendMail(
3079  $recipient, // to
3080  "", // cc
3081  "", // bcc
3082  $this->lng->txt('finished_mail_subject') . ': ' . $this->getTitle(), // subject
3083  $messagetext, // message
3084  array(), // attachments
3085  array('normal') // type
3086  );
3087  }
3088  }
3089 
3090  protected function getParticipantTextResults($active_id)
3091  {
3092  $textresult = "";
3093  $userResults =& $this->getUserSpecificResults();
3094  $questions =& $this->getSurveyQuestions(true);
3095  $questioncounter = 1;
3096  foreach ($questions as $question_id => $question_data)
3097  {
3098  $textresult .= $questioncounter++ . ". " . $question_data["title"] . "\n";
3099  $found = $userResults[$question_id][$active_id];
3100  $text = "";
3101  if (is_array($found))
3102  {
3103  $text = implode("\n", $found);
3104  }
3105  else
3106  {
3107  $text = $found;
3108  }
3109  if (strlen($text) == 0) $text = $this->lng->txt("skipped");
3110  $text = str_replace("<br />", "\n", $text);
3111  $textresult .= $text . "\n\n";
3112  }
3113  return $textresult;
3114  }
3115 
3117  {
3118  $counter = 0;
3119  $questions =& $this->getSurveyQuestions();
3120  $counter++;
3121  foreach ($questions as $data)
3122  {
3123  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
3124  $question = SurveyQuestion::_instanciateQuestion($data["question_id"]);
3125 
3126  $eval = $this->getCumulatedResults($question);
3127  }
3128  }
3129 
3137  function isAllowedToTakeMultipleSurveys($userid = "")
3138  {
3139  // #7927: special users are deprecated
3140  return false;
3141 
3142  /*
3143  $result = FALSE;
3144  if ($this->getAnonymize())
3145  {
3146  if ($this->isAccessibleWithoutCode())
3147  {
3148  if (strlen($username) == 0)
3149  {
3150  global $ilUser;
3151  $userid = $ilUser->getId();
3152  }
3153  global $ilSetting;
3154  $surveysetting = new ilSetting("survey");
3155  $allowedUsers = strlen($surveysetting->get("multiple_survey_users")) ? explode(",",$surveysetting->get("multiple_survey_users")) : array();
3156  if (in_array($userid, $allowedUsers))
3157  {
3158  $result = TRUE;
3159  }
3160  }
3161  }
3162  return $result;
3163  */
3164  }
3165 
3173  function isSurveyStarted($user_id, $anonymize_id)
3174  {
3175  global $ilDB;
3176 
3177  if ($this->getAnonymize())
3178  {
3179  if ((($user_id != ANONYMOUS_USER_ID) && sizeof($anonymize_id)) && (!($this->isAccessibleWithoutCode() && $this->isAllowedToTakeMultipleSurveys())))
3180  {
3181  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
3182  array('integer','integer'),
3183  array($this->getSurveyId(), $user_id)
3184  );
3185  }
3186  else
3187  {
3188  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s AND anonymous_id = %s",
3189  array('integer','text'),
3190  array($this->getSurveyId(), $anonymize_id)
3191  );
3192  }
3193  }
3194  else
3195  {
3196  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
3197  array('integer','integer'),
3198  array($this->getSurveyId(), $user_id)
3199  );
3200  }
3201  if ($result->numRows() == 0)
3202  {
3203  return false;
3204  }
3205  else
3206  {
3207  $row = $ilDB->fetchAssoc($result);
3208  $_SESSION["finished_id"][$this->getId()] = $row["finished_id"];
3209  return (int)$row["state"];
3210  }
3211  }
3212 
3220  function getActiveID($user_id, $anonymize_id)
3221  {
3222  global $ilDB;
3223 
3224  if ($this->getAnonymize())
3225  {
3226  if ((($user_id != ANONYMOUS_USER_ID) && (strlen($anonymize_id) == 0)) && (!($this->isAccessibleWithoutCode() && $this->isAllowedToTakeMultipleSurveys())))
3227  {
3228  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
3229  array('integer','integer'),
3230  array($this->getSurveyId(), $user_id)
3231  );
3232  }
3233  else
3234  {
3235  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s AND anonymous_id = %s",
3236  array('integer','text'),
3237  array($this->getSurveyId(), $anonymize_id)
3238  );
3239  }
3240  }
3241  else
3242  {
3243  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
3244  array('integer','integer'),
3245  array($this->getSurveyId(), $user_id)
3246  );
3247  }
3248  if ($result->numRows() == 0)
3249  {
3250  return false;
3251  }
3252  else
3253  {
3254  $row = $ilDB->fetchAssoc($result);
3255  return $row["finished_id"];
3256  }
3257  }
3258 
3266  function getLastActivePage($active_id)
3267  {
3268  global $ilDB;
3269  $result = $ilDB->queryF("SELECT lastpage FROM svy_finished WHERE finished_id = %s",
3270  array('integer'),
3271  array($active_id)
3272  );
3273  if ($result->numRows() == 0)
3274  {
3275  return "";
3276  }
3277  else
3278  {
3279  $row = $ilDB->fetchAssoc($result);
3280  return ($row["lastpage"]) ? $row["lastpage"] : '';
3281  }
3282  }
3283 
3292  function checkConstraint($constraint_data, $working_data)
3293  {
3294  if (count($working_data) == 0)
3295  {
3296  return 0;
3297  }
3298 
3299  if ((count($working_data) == 1) and (strcmp($working_data[0]["value"], "") == 0))
3300  {
3301  return 0;
3302  }
3303 
3304  $found = false;
3305  foreach ($working_data as $data)
3306  {
3307  switch ($constraint_data["short"])
3308  {
3309  case "<":
3310  if ($data["value"] < $constraint_data["value"])
3311  {
3312  $found = true;
3313  }
3314  break;
3315 
3316  case "<=":
3317  if ($data["value"] <= $constraint_data["value"])
3318  {
3319  $found = true;
3320  }
3321  break;
3322 
3323  case "=":
3324  if ($data["value"] == $constraint_data["value"])
3325  {
3326  $found = true;
3327  }
3328  break;
3329 
3330  case "<>":
3331  if ($data["value"] <> $constraint_data["value"])
3332  {
3333  $found = true;
3334  }
3335  break;
3336 
3337  case ">=":
3338  if ($data["value"] >= $constraint_data["value"])
3339  {
3340  $found = true;
3341  }
3342  break;
3343 
3344  case ">":
3345  if ($data["value"] > $constraint_data["value"])
3346  {
3347  $found = true;
3348  }
3349  break;
3350  }
3351  if ($found)
3352  {
3353  break;
3354  }
3355  }
3356 
3357  return (int)$found;
3358  }
3359 
3361  {
3362  global $ilDB;
3363 
3364  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
3365  array('integer'),
3366  array($survey_id)
3367  );
3368  return ($result->numRows()) ? true : false;
3369  }
3370 
3378  {
3379  global $ilDB, $ilLog;
3380 
3381  $users = array();
3382  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s",
3383  array('integer'),
3384  array($this->getSurveyId())
3385  );
3386  if ($result->numRows())
3387  {
3388  while ($row = $ilDB->fetchAssoc($result))
3389  {
3390  array_push($users, $row["finished_id"]);
3391  }
3392  }
3393  return $users;
3394  }
3395 
3403  {
3404  global $ilDB;
3405 
3406  $users = array();
3407  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE survey_fi = %s",
3408  array('integer'),
3409  array($this->getSurveyId())
3410  );
3411  if ($result->numRows())
3412  {
3413  while ($row = $ilDB->fetchAssoc($result))
3414  {
3415  array_push($users, $row);
3416  }
3417  }
3418  $evaluation = array();
3419  $questions =& $this->getSurveyQuestions();
3420  foreach ($questions as $question_id => $question_data)
3421  {
3422  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
3423  $question_type = SurveyQuestion::_getQuestionType($question_id);
3424  SurveyQuestion::_includeClass($question_type);
3425  $question = new $question_type();
3426  $question->loadFromDb($question_id);
3427  $data =& $question->getUserAnswers($this->getSurveyId());
3428  $evaluation[$question_id] = $data;
3429  }
3430  return $evaluation;
3431  }
3432 
3440  function getUserDataFromActiveId($active_id)
3441  {
3442  global $ilDB;
3443 
3444  $surveySetting = new ilSetting("survey");
3445  $use_anonymous_id = array_key_exists("use_anonymous_id", $_GET) ? $_GET["use_anonymous_id"] : $surveySetting->get("use_anonymous_id");
3446  $result = $ilDB->queryF("SELECT * FROM svy_finished WHERE finished_id = %s",
3447  array('integer'),
3448  array($active_id)
3449  );
3450  $row = array();
3451  $foundrows = $result->numRows();
3452  if ($foundrows)
3453  {
3454  $row = $ilDB->fetchAssoc($result);
3455  }
3456  $name = ($use_anonymous_id) ? $row["anonymous_id"] : $this->lng->txt("anonymous");
3457  $userdata = array(
3458  "fullname" => $name,
3459  "sortname" => $name,
3460  "firstname" => "",
3461  "lastname" => "",
3462  "login" => "",
3463  "gender" => "",
3464  "active_id" => "$active_id"
3465  );
3466  if ($foundrows)
3467  {
3468  if (($row["user_fi"] > 0) && ($row["user_fi"] != ANONYMOUS_USER_ID) && ($this->getAnonymize() == 0))
3469  {
3470  include_once './Services/User/classes/class.ilObjUser.php';
3471  if (strlen(ilObjUser::_lookupLogin($row["user_fi"])) == 0)
3472  {
3473  $userdata["fullname"] = $userdata["sortname"] = $this->lng->txt("deleted_user");
3474  }
3475  else
3476  {
3477  $user = new ilObjUser($row["user_fi"]);
3478  $userdata["fullname"] = $user->getFullname();
3479  $gender = $user->getGender();
3480  if (strlen($gender) == 1) $gender = $this->lng->txt("gender_$gender");
3481  $userdata["gender"] = $gender;
3482  $userdata["firstname"] = $user->getFirstname();
3483  $userdata["lastname"] = $user->getLastname();
3484  $userdata["sortname"] = $user->getLastname() . ", " . $user->getFirstname();
3485  $userdata["login"] = $user->getLogin();
3486  }
3487  }
3488  }
3489  return $userdata;
3490  }
3491 
3501  function &getEvaluationByUser($questions, $active_id)
3502  {
3503  global $ilDB;
3504 
3505  // collect all answers
3506  $answers = array();
3507  $result = $ilDB->queryF("SELECT * FROM svy_answer WHERE active_fi = %s",
3508  array('integer'),
3509  array($active_id)
3510  );
3511  while ($row = $ilDB->fetchAssoc($result))
3512  {
3513  if (!is_array($answers[$row["question_fi"]]))
3514  {
3515  $answers[$row["question_fi"]] = array();
3516  }
3517  array_push($answers[$row["question_fi"]], $row);
3518  }
3519  $userdata = $this->getUserDataFromActiveId($active_id);
3520  $resultset = array(
3521  "name" => $userdata["fullname"],
3522  "firstname" => $userdata["firstname"],
3523  "lastname" => $userdata["lastname"],
3524  "login" => $userdata["login"],
3525  "gender" => $userdata["gender"],
3526  "answers" => array()
3527  );
3528  foreach ($questions as $key => $question)
3529  {
3530  if (array_key_exists($key, $answers))
3531  {
3532  $resultset["answers"][$key] = $answers[$key];
3533  }
3534  else
3535  {
3536  $resultset["answers"][$key] = array();
3537  }
3538  sort($resultset["answers"][$key]);
3539  }
3540  return $resultset;
3541  }
3542 
3551  function getCumulatedResults(&$question)
3552  {
3553  global $ilDB;
3554 
3555  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
3556  array('integer'),
3557  array($this->getSurveyId())
3558  );
3559  $nr_of_users = $result->numRows();
3560 
3561  $result_array =& $question->getCumulatedResults($this->getSurveyId(), $nr_of_users);
3562  return $result_array;
3563  }
3564 
3573  {
3574  global $ilDB;
3575 
3576  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s",
3577  array('integer'),
3578  array($survey_id)
3579  );
3580  return $result->numRows();
3581  }
3582 
3583  function &getQuestions($question_ids)
3584  {
3585  global $ilDB;
3586 
3587  $result_array = array();
3588  $result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag FROM svy_question, svy_qtype WHERE ".
3589  "svy_question.questiontype_fi = svy_qtype.questiontype_id AND svy_question.tstamp > 0 AND ".
3590  $ilDB->in('svy_question.question_id', $question_ids, false, 'integer'));
3591  while ($row = $ilDB->fetchAssoc($result))
3592  {
3593  array_push($result_array, $row);
3594  }
3595  return $result_array;
3596  }
3597 
3603  function getQuestionsTable($arrFilter)
3604  {
3605  global $ilUser;
3606  global $ilDB;
3607  $where = "";
3608  if (is_array($arrFilter))
3609  {
3610  if (array_key_exists('title', $arrFilter) && strlen($arrFilter['title']))
3611  {
3612  $where .= " AND " . $ilDB->like('svy_question.title', 'text', "%%" . $arrFilter['title'] . "%%");
3613  }
3614  if (array_key_exists('description', $arrFilter) && strlen($arrFilter['description']))
3615  {
3616  $where .= " AND " . $ilDB->like('svy_question.description', 'text', "%%" . $arrFilter['description'] . "%%");
3617  }
3618  if (array_key_exists('author', $arrFilter) && strlen($arrFilter['author']))
3619  {
3620  $where .= " AND " . $ilDB->like('svy_question.author', 'text', "%%" . $arrFilter['author'] . "%%");
3621  }
3622  if (array_key_exists('type', $arrFilter) && strlen($arrFilter['type']))
3623  {
3624  $where .= " AND svy_qtype.type_tag = " . $ilDB->quote($arrFilter['type'], 'text');
3625  }
3626  if (array_key_exists('spl', $arrFilter) && strlen($arrFilter['spl']))
3627  {
3628  $where .= " AND svy_question.obj_fi = " . $ilDB->quote($arrFilter['spl'], 'integer');
3629  }
3630  }
3631 
3632  $spls =& $this->getAvailableQuestionpools($use_obj_id = TRUE, $could_be_offline = FALSE, $showPath = FALSE);
3633  $forbidden = "";
3634  $forbidden = " AND " . $ilDB->in('svy_question.obj_fi', array_keys($spls), false, 'integer');
3635  $forbidden .= " AND svy_question.complete = " . $ilDB->quote("1", 'text');
3636  $existing = "";
3637  $existing_questions =& $this->getExistingQuestions();
3638  if (count($existing_questions))
3639  {
3640  $existing = " AND " . $ilDB->in('svy_question.question_id', $existing_questions, true, 'integer');
3641  }
3642 
3643  include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php";
3645 
3646  $query_result = $ilDB->query("SELECT svy_question.*, svy_qtype.type_tag, svy_qtype.plugin, object_reference.ref_id".
3647  " FROM svy_question, svy_qtype, object_reference".
3648  " WHERE svy_question.original_id IS NULL".$forbidden.$existing.
3649  " AND svy_question.obj_fi = object_reference.obj_id AND svy_question.tstamp > 0".
3650  " 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  if (array_key_exists('spl_txt', $arrFilter) && strlen($arrFilter['spl_txt']))
3658  {
3659  if(!stristr($spls[$row["obj_fi"]], $arrFilter['spl_txt']))
3660  {
3661  continue;
3662  }
3663  }
3664 
3665  $row['ttype'] = $trans[$row['type_tag']];
3666  if ($row["plugin"])
3667  {
3668  if ($this->isPluginActive($row["type_tag"]))
3669  {
3670  array_push($rows, $row);
3671  }
3672  }
3673  else
3674  {
3675  array_push($rows, $row);
3676  }
3677  }
3678  }
3679  return $rows;
3680  }
3681 
3687  function getQuestionblocksTable($arrFilter)
3688  {
3689  global $ilUser, $ilDB;
3690 
3691  $where = "";
3692  if (is_array($arrFilter))
3693  {
3694  if (array_key_exists('title', $arrFilter) && strlen($arrFilter['title']))
3695  {
3696  $where .= " AND " . $ilDB->like('svy_qblk.title', 'text', "%%" . $arrFilter['title'] . "%%");
3697  }
3698  }
3699 
3700  $query_result = $ilDB->query("SELECT svy_qblk.*, svy_svy.obj_fi FROM svy_qblk , svy_qblk_qst, svy_svy WHERE ".
3701  "svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND svy_svy.survey_id = svy_qblk_qst.survey_fi ".
3702  "$where GROUP BY svy_qblk.questionblock_id, svy_qblk.title, svy_qblk.show_questiontext, svy_qblk.show_blocktitle, ".
3703  "svy_qblk.owner_fi, svy_qblk.tstamp, svy_svy.obj_fi");
3704  $rows = array();
3705  if ($query_result->numRows())
3706  {
3707  $survey_ref_ids = ilUtil::_getObjectsByOperations("svy", "write");
3708  $surveytitles = array();
3709  foreach ($survey_ref_ids as $survey_ref_id)
3710  {
3711  $survey_id = ilObject::_lookupObjId($survey_ref_id);
3712  $surveytitles[$survey_id] = ilObject::_lookupTitle($survey_id);
3713  }
3714  while ($row = $ilDB->fetchAssoc($query_result))
3715  {
3716  $questions_array =& $this->getQuestionblockQuestions($row["questionblock_id"]);
3717  $counter = 1;
3718  foreach ($questions_array as $key => $value)
3719  {
3720  $questions_array[$key] = "$counter. $value";
3721  $counter++;
3722  }
3723  if (strlen($surveytitles[$row["obj_fi"]])) // only questionpools which are not in trash
3724  {
3725  $rows[$row["questionblock_id"]] = array(
3726  "questionblock_id" => $row["questionblock_id"],
3727  "title" => $row["title"],
3728  "svy" => $surveytitles[$row["obj_fi"]],
3729  "contains" => join($questions_array, ", "),
3730  "owner" => $row["owner_fi"]
3731  );
3732  }
3733  }
3734  }
3735  return $rows;
3736  }
3737 
3744  function toXML()
3745  {
3746  include_once("./Services/Xml/classes/class.ilXmlWriter.php");
3747  $a_xml_writer = new ilXmlWriter;
3748  // set xml header
3749  $a_xml_writer->xmlHeader();
3750  $attrs = array(
3751  "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
3752  "xsi:noNamespaceSchemaLocation" => "http://www.ilias.de/download/xsd/ilias_survey_4_2.xsd"
3753  );
3754  $a_xml_writer->xmlStartTag("surveyobject", $attrs);
3755  $attrs = array(
3756  "id" => $this->getSurveyId(),
3757  "title" => $this->getTitle()
3758  );
3759  $a_xml_writer->xmlStartTag("survey", $attrs);
3760 
3761  $a_xml_writer->xmlElement("description", NULL, $this->getDescription());
3762  $a_xml_writer->xmlElement("author", NULL, $this->getAuthor());
3763  $a_xml_writer->xmlStartTag("objectives");
3764  $attrs = array(
3765  "label" => "introduction"
3766  );
3767  $this->addMaterialTag($a_xml_writer, $this->getIntroduction(), TRUE, TRUE, $attrs);
3768  $attrs = array(
3769  "label" => "outro"
3770  );
3771  $this->addMaterialTag($a_xml_writer, $this->getOutro(), TRUE, TRUE, $attrs);
3772  $a_xml_writer->xmlEndTag("objectives");
3773 
3774  if ($this->getAnonymize())
3775  {
3776  $attribs = array("enabled" => "1");
3777  }
3778  else
3779  {
3780  $attribs = array("enabled" => "0");
3781  }
3782  $a_xml_writer->xmlElement("anonymisation", $attribs);
3783  $a_xml_writer->xmlStartTag("restrictions");
3784  if ($this->getAnonymize() == 2)
3785  {
3786  $attribs = array("type" => "free");
3787  }
3788  else
3789  {
3790  $attribs = array("type" => "restricted");
3791  }
3792  $a_xml_writer->xmlElement("access", $attribs);
3793  if ($this->getStartDate())
3794  {
3795  $attrs = array("type" => "date");
3796  preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getStartDate(), $matches);
3797  $a_xml_writer->xmlElement("startingtime", $attrs, sprintf("%04d-%02d-%02dT%02d:%02d:00", $matches[1], $matches[2], $matches[3], $matches[4], $matches[5], $matches[6]));
3798  }
3799  if ($this->getEndDate())
3800  {
3801  $attrs = array("type" => "date");
3802  preg_match("/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/", $this->getEndDate(), $matches);
3803  $a_xml_writer->xmlElement("endingtime", $attrs, sprintf("%04d-%02d-%02dT%02d:%02d:00", $matches[1], $matches[2], $matches[3], $matches[4], $matches[5], $matches[6]));
3804 
3805  }
3806  $a_xml_writer->xmlEndTag("restrictions");
3807 
3808  // constraints
3809  $pages =& $this->getSurveyPages();
3810  $hasconstraints = FALSE;
3811  foreach ($pages as $question_array)
3812  {
3813  foreach ($question_array as $question)
3814  {
3815  if (count($question["constraints"]))
3816  {
3817  $hasconstraints = TRUE;
3818  }
3819  }
3820  }
3821 
3822  if ($hasconstraints)
3823  {
3824  $a_xml_writer->xmlStartTag("constraints");
3825  foreach ($pages as $question_array)
3826  {
3827  foreach ($question_array as $question)
3828  {
3829  if (count($question["constraints"]))
3830  {
3831  // found constraints
3832  foreach ($question["constraints"] as $constraint)
3833  {
3834  $attribs = array(
3835  "sourceref" => $question["question_id"],
3836  "destref" => $constraint["question"],
3837  "relation" => $constraint["short"],
3838  "value" => $constraint["value"],
3839  "conjunction" => $constraint["conjunction"]
3840  );
3841  $a_xml_writer->xmlElement("constraint", $attribs);
3842  }
3843  }
3844  }
3845  }
3846  $a_xml_writer->xmlEndTag("constraints");
3847  }
3848 
3849  // add the rest of the preferences in qtimetadata tags, because there is no correspondent definition in QTI
3850  $a_xml_writer->xmlStartTag("metadata");
3851 
3852  $a_xml_writer->xmlStartTag("metadatafield");
3853  $a_xml_writer->xmlElement("fieldlabel", NULL, "evaluation_access");
3854  $a_xml_writer->xmlElement("fieldentry", NULL, $this->getEvaluationAccess());
3855  $a_xml_writer->xmlEndTag("metadatafield");
3856 
3857  $a_xml_writer->xmlStartTag("metadatafield");
3858  $a_xml_writer->xmlElement("fieldlabel", NULL, "status");
3859  $a_xml_writer->xmlElement("fieldentry", NULL, $this->getStatus());
3860  $a_xml_writer->xmlEndTag("metadatafield");
3861 
3862  $a_xml_writer->xmlStartTag("metadatafield");
3863  $a_xml_writer->xmlElement("fieldlabel", NULL, "display_question_titles");
3864  $a_xml_writer->xmlElement("fieldentry", NULL, $this->getShowQuestionTitles());
3865  $a_xml_writer->xmlEndTag("metadatafield");
3866 
3867  $a_xml_writer->xmlStartTag("metadatafield");
3868  $a_xml_writer->xmlElement("fieldlabel", NULL, "SCORM");
3869  include_once "./Services/MetaData/classes/class.ilMD.php";
3870  $md = new ilMD($this->getId(),0, $this->getType());
3871  $writer = new ilXmlWriter();
3872  $md->toXml($writer);
3873  $metadata = $writer->xmlDumpMem();
3874  $a_xml_writer->xmlElement("fieldentry", NULL, $metadata);
3875  $a_xml_writer->xmlEndTag("metadatafield");
3876 
3877  $a_xml_writer->xmlEndTag("metadata");
3878  $a_xml_writer->xmlEndTag("survey");
3879 
3880  $attribs = array("id" => $this->getId());
3881  $a_xml_writer->xmlStartTag("surveyquestions", $attribs);
3882  // add questionblock descriptions
3883  $obligatory_states =& $this->getObligatoryStates();
3884  foreach ($pages as $question_array)
3885  {
3886  if (count($question_array) > 1)
3887  {
3888  $attribs = array("id" => $question_array[0]["question_id"]);
3889  $attribs = array("showQuestiontext" => $question_array[0]["questionblock_show_questiontext"],
3890  "showBlocktitle" => $question_array[0]["questionblock_show_blocktitle"]);
3891  $a_xml_writer->xmlStartTag("questionblock", $attribs);
3892  if (strlen($question_array[0]["questionblock_title"]))
3893  {
3894  $a_xml_writer->xmlElement("questionblocktitle", NULL, $question_array[0]["questionblock_title"]);
3895  }
3896  }
3897  foreach ($question_array as $question)
3898  {
3899  if (strlen($question["heading"]))
3900  {
3901  $a_xml_writer->xmlElement("textblock", NULL, $question["heading"]);
3902  }
3903  $questionObject =& $this->_instanciateQuestion($question["question_id"]);
3904  if ($questionObject !== FALSE) $questionObject->insertXML($a_xml_writer, FALSE, $obligatory_states[$question["question_id"]]);
3905  }
3906  if (count($question_array) > 1)
3907  {
3908  $a_xml_writer->xmlEndTag("questionblock");
3909  }
3910  }
3911 
3912  $a_xml_writer->xmlEndTag("surveyquestions");
3913  $a_xml_writer->xmlEndTag("surveyobject");
3914  $xml = $a_xml_writer->xmlDumpMem(FALSE);
3915  return $xml;
3916  }
3917 
3925  function &_instanciateQuestion($question_id)
3926  {
3927  if ($question_id < 1) return FALSE;
3928  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
3929  $question_type = SurveyQuestion::_getQuestionType($question_id);
3930  if (strlen($question_type) == 0) return FALSE;
3931  SurveyQuestion::_includeClass($question_type);
3932  $question = new $question_type();
3933  $question->loadFromDb($question_id);
3934  return $question;
3935  }
3936 
3943  function locateImportFiles($a_dir)
3944  {
3945  if (!is_dir($a_dir) || is_int(strpos($a_dir, "..")))
3946  {
3947  return;
3948  }
3949  $importDirectory = "";
3950  $xmlFile = "";
3951 
3952  $current_dir = opendir($a_dir);
3953  $files = array();
3954  while($entryname = readdir($current_dir))
3955  {
3956  $files[] = $entryname;
3957  }
3958 
3959  foreach($files as $file)
3960  {
3961  if(is_dir($a_dir."/".$file) and ($file != "." and $file!=".."))
3962  {
3963  // found directory created by zip
3964  $importDirectory = $a_dir."/".$file;
3965  }
3966  }
3967  closedir($current_dir);
3968  if (strlen($importDirectory))
3969  {
3970  // find the xml file
3971  $current_dir = opendir($importDirectory);
3972  $files = array();
3973  while($entryname = readdir($current_dir))
3974  {
3975  $files[] = $entryname;
3976  }
3977  foreach($files as $file)
3978  {
3979  if(@is_file($importDirectory."/".$file) && ($file != "." && $file!="..") && (ereg("^[0-9]{10}_{2}[0-9]+_{2}(svy_)*[0-9]+\.[a-z]{1,3}\$", $file) || ereg("^[0-9]{10}_{2}[0-9]+_{2}(survey__)*[0-9]+\.[a-z]{1,3}\$", $file)))
3980  {
3981  // found xml file
3982  $xmlFile = $importDirectory."/".$file;
3983  }
3984  }
3985  }
3986  return array("dir" => $importDirectory, "xml" => $xmlFile);
3987  }
3988 
3995  function importObject($file_info, $svy_qpl_id)
3996  {
3997  if ($svy_qpl_id < 1) $svy_qpl_id = -1;
3998  // check if file was uploaded
3999  $source = $file_info["tmp_name"];
4000  $error = "";
4001  if (($source == 'none') || (!$source) || $file_info["error"] > UPLOAD_ERR_OK)
4002  {
4003  $error = $this->lng->txt("import_no_file_selected");
4004  }
4005  // check correct file type
4006  $isXml = FALSE;
4007  $isZip = FALSE;
4008  if ((strcmp($file_info["type"], "text/xml") == 0) || (strcmp($file_info["type"], "application/xml") == 0))
4009  {
4010  $isXml = TRUE;
4011  }
4012  // too many different mime-types, so we use the suffix
4013  $suffix = pathinfo($file_info["name"]);
4014  if (strcmp(strtolower($suffix["extension"]), "zip") == 0)
4015  {
4016  $isZip = TRUE;
4017  }
4018  if (!$isXml && !$isZip)
4019  {
4020  $error = $this->lng->txt("import_wrong_file_type");
4021  global $ilLog;
4022  $ilLog->write("Survey: Import error. Filetype was \"" . $file_info["type"] ."\"");
4023  }
4024  if (strlen($error) == 0)
4025  {
4026  // import file as a survey
4027  $import_dir = $this->getImportDirectory();
4028  $import_subdir = "";
4029  $importfile = "";
4030  include_once "./Services/Utilities/classes/class.ilUtil.php";
4031  if ($isZip)
4032  {
4033  $importfile = $import_dir."/".$file_info["name"];
4034  ilUtil::moveUploadedFile($source, $file_info["name"], $importfile);
4035  ilUtil::unzip($importfile);
4036  $found = $this->locateImportFiles($import_dir);
4037  if (!((strlen($found["dir"]) > 0) && (strlen($found["xml"]) > 0)))
4038  {
4039  $error = $this->lng->txt("wrong_import_file_structure");
4040  return $error;
4041  }
4042  $importfile = $found["xml"];
4043  $import_subdir = $found["dir"];
4044  }
4045  else
4046  {
4047  $importfile = tempnam($import_dir, "survey_import");
4048  ilUtil::moveUploadedFile($source, $file_info["name"], $importfile);
4049  }
4050  $fh = fopen($importfile, "r");
4051  if (!$fh)
4052  {
4053  $error = $this->lng->txt("import_error_opening_file");
4054  return $error;
4055  }
4056  $xml = fread($fh, filesize($importfile));
4057  $result = fclose($fh);
4058  if (!$result)
4059  {
4060  $error = $this->lng->txt("import_error_closing_file");
4061  return $error;
4062  }
4063 
4064  unset($_SESSION["import_mob_xhtml"]);
4065  if (strpos($xml, "questestinterop"))
4066  {
4067  include_once "./Services/Survey/classes/class.SurveyImportParserPre38.php";
4068  $import = new SurveyImportParserPre38($svy_qpl_id, "", TRUE);
4069  $import->setSurveyObject($this);
4070  $import->setXMLContent($xml);
4071  $import->startParsing();
4072  }
4073  else
4074  {
4075  include_once "./Services/Survey/classes/class.SurveyImportParser.php";
4076  $import = new SurveyImportParser($svy_qpl_id, "", TRUE);
4077  $import->setSurveyObject($this);
4078  $import->setXMLContent($xml);
4079  $import->startParsing();
4080  }
4081 
4082  if (is_array($_SESSION["import_mob_xhtml"]))
4083  {
4084  include_once "./Services/MediaObjects/classes/class.ilObjMediaObject.php";
4085  include_once "./Services/RTE/classes/class.ilRTE.php";
4086  include_once "./Modules/TestQuestionPool/classes/class.ilObjQuestionPool.php";
4087  foreach ($_SESSION["import_mob_xhtml"] as $mob)
4088  {
4089  $importfile = $import_subdir . "/" . $mob["uri"];
4090  if (file_exists($importfile))
4091  {
4092  $media_object =& ilObjMediaObject::_saveTempFileAsMediaObject(basename($importfile), $importfile, FALSE);
4093  ilObjMediaObject::_saveUsage($media_object->getId(), "svy:html", $this->getId());
4094  $this->setIntroduction(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $this->getIntroduction()));
4095  $this->setOutro(str_replace("src=\"" . $mob["mob"] . "\"", "src=\"" . "il_" . IL_INST_ID . "_mob_" . $media_object->getId() . "\"", $this->getOutro()));
4096  }
4097  else
4098  {
4099  global $ilLog;
4100  $ilLog->write("Error: Could not open XHTML mob file for test introduction during test import. File $importfile does not exist!");
4101  }
4102  }
4105  $this->saveToDb();
4106  }
4107 
4108  // delete import directory
4110  }
4111  return $error;
4112  }
4113 
4122  public function cloneObject($a_target_id,$a_copy_id = 0)
4123  {
4124  global $ilDB;
4125 
4126  $this->loadFromDb();
4127 
4128  // Copy settings
4129  $newObj = parent::cloneObject($a_target_id,$a_copy_id);
4130  $this->cloneMetaData($newObj);
4131  $newObj->updateMetaData();
4132 
4133  $newObj->setAuthor($this->getAuthor());
4134  $newObj->setIntroduction($this->getIntroduction());
4135  $newObj->setOutro($this->getOutro());
4136  $newObj->setStatus($this->getStatus());
4137  $newObj->setEvaluationAccess($this->getEvaluationAccess());
4138  $newObj->setStartDate($this->getStartDate());
4139  $newObj->setEndDate($this->getEndDate());
4140  $newObj->setInvitation($this->getInvitation());
4141  $newObj->setInvitationMode($this->getInvitationMode());
4142  $newObj->setAnonymize($this->getAnonymize());
4143  $newObj->setShowQuestionTitles($this->getShowQuestionTitles());
4144  $newObj->setTemplate($this->getTemplate());
4145 
4146 
4147  $question_pointer = array();
4148  // clone the questions
4149  $mapping = array();
4150  include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php";
4151  foreach ($this->questions as $key => $question_id)
4152  {
4153  $question = ilObjSurvey::_instanciateQuestion($question_id);
4154  if($question) // #10824
4155  {
4156  $question->id = -1;
4157  $original_id = SurveyQuestion::_getOriginalId($question_id, false);
4158  $question->saveToDb($original_id);
4159  $newObj->questions[$key] = $question->getId();
4160  $question_pointer[$question_id] = $question->getId();
4161  $mapping[$question_id] = $question->getId();
4162  }
4163  }
4164 
4165  $newObj->saveToDb();
4166  $newObj->cloneTextblocks($mapping);
4167 
4168  // clone the questionblocks
4169  $questionblocks = array();
4170  $questionblock_questions = array();
4171  $result = $ilDB->queryF("SELECT * FROM svy_qblk_qst WHERE survey_fi = %s",
4172  array('integer'),
4173  array($this->getSurveyId())
4174  );
4175  if ($result->numRows() > 0)
4176  {
4177  while ($row = $ilDB->fetchAssoc($result))
4178  {
4179  array_push($questionblock_questions, $row);
4180  $questionblocks[$row["questionblock_fi"]] = $row["questionblock_fi"];
4181  }
4182  }
4183  // create new questionblocks
4184  foreach ($questionblocks as $key => $value)
4185  {
4186  $questionblock = ilObjSurvey::_getQuestionblock($key);
4187  $questionblock_id = ilObjSurvey::_addQuestionblock($questionblock["title"], $questionblock["owner_fi"], $questionblock["show_questiontext"], $questionblock["show_blocktitle"]);
4188  $questionblocks[$key] = $questionblock_id;
4189  }
4190  // create new questionblock questions
4191  foreach ($questionblock_questions as $key => $value)
4192  {
4193  if($questionblocks[$value["questionblock_fi"]] &&
4194  $question_pointer[$value["question_fi"]])
4195  {
4196  $next_id = $ilDB->nextId('svy_qblk_qst');
4197  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qblk_qst (qblk_qst_id, survey_fi, questionblock_fi, question_fi) ".
4198  "VALUES (%s, %s, %s, %s)",
4199  array('integer','integer','integer','integer'),
4200  array($next_id, $newObj->getSurveyId(), $questionblocks[$value["questionblock_fi"]], $question_pointer[$value["question_fi"]])
4201  );
4202  }
4203  }
4204 
4205  // clone the constraints
4206  $constraints = ilObjSurvey::_getConstraints($this->getSurveyId());
4207  $newConstraints = array();
4208  foreach ($constraints as $key => $constraint)
4209  {
4210  if ($question_pointer[$constraint["for_question"]] &&
4211  $question_pointer[$constraint["question"]])
4212  {
4213  if (!array_key_exists($constraint['id'], $newConstraints))
4214  {
4215  $constraint_id = $newObj->addConstraint($question_pointer[$constraint["question"]], $constraint["relation_id"], $constraint["value"], $constraint['conjunction']);
4216  $newConstraints[$constraint['id']] = $constraint_id;
4217  }
4218  $newObj->addConstraintToQuestion($question_pointer[$constraint["for_question"]], $newConstraints[$constraint['id']]);
4219  }
4220  }
4221 
4222  // clone the obligatory states
4223  $result = $ilDB->queryF("SELECT * FROM svy_qst_oblig WHERE survey_fi = %s",
4224  array('integer'),
4225  array($this->getSurveyId())
4226  );
4227  if ($result->numRows() > 0)
4228  {
4229  while ($row = $ilDB->fetchAssoc($result))
4230  {
4231  if($question_pointer[$row["question_fi"]])
4232  {
4233  $next_id = $ilDB->nextId('svy_qst_oblig');
4234  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_qst_oblig (question_obligatory_id, survey_fi, question_fi, ".
4235  "obligatory, tstamp) VALUES (%s, %s, %s, %s, %s)",
4236  array('integer','integer','integer','text','integer'),
4237  array($next_id, $newObj->getSurveyId(), $question_pointer[$row["question_fi"]], $row["obligatory"], time())
4238  );
4239  }
4240  }
4241  }
4242  return $newObj;
4243  }
4244 
4245  function getTextblock($question_id)
4246  {
4247  global $ilDB;
4248  $result = $ilDB->queryF("SELECT * FROM svy_svy_qst WHERE question_fi = %s",
4249  array('integer'),
4250  array($question_id)
4251  );
4252  if ($result->numRows())
4253  {
4254  $row = $ilDB->fetchAssoc($result);
4255  return $row["heading"];
4256  }
4257  else
4258  {
4259  return "";
4260  }
4261  }
4262 
4268  function cloneTextblocks($mapping)
4269  {
4270  foreach ($mapping as $original_id => $new_id)
4271  {
4272  $textblock = $this->getTextblock($original_id);
4273  include_once "./Services/AdvancedEditing/classes/class.ilObjAdvancedEditing.php";
4274  $this->saveHeading(ilUtil::stripSlashes($textblock, TRUE, ilObjAdvancedEditing::_getUsedHTMLTagsAsString("survey")), $new_id);
4275  }
4276  }
4277 
4284  {
4285  include_once "./Services/Utilities/classes/class.ilUtil.php";
4286  $svy_data_dir = ilUtil::getDataDir()."/svy_data";
4287  ilUtil::makeDir($svy_data_dir);
4288  if(!is_writable($svy_data_dir))
4289  {
4290  $this->ilias->raiseError("Survey Data Directory (".$svy_data_dir
4291  .") not writeable.",$this->ilias->error_obj->FATAL);
4292  }
4293 
4294  // create learning module directory (data_dir/lm_data/lm_<id>)
4295  $svy_dir = $svy_data_dir."/svy_".$this->getId();
4296  ilUtil::makeDir($svy_dir);
4297  if(!@is_dir($svy_dir))
4298  {
4299  $this->ilias->raiseError("Creation of Survey Directory failed.",$this->ilias->error_obj->FATAL);
4300  }
4301  // create Export subdirectory (data_dir/lm_data/lm_<id>/Export)
4302  $export_dir = $svy_dir."/export";
4303  ilUtil::makeDir($export_dir);
4304  if(!@is_dir($export_dir))
4305  {
4306  $this->ilias->raiseError("Creation of Export Directory failed.",$this->ilias->error_obj->FATAL);
4307  }
4308  }
4309 
4314  {
4315  include_once "./Services/Utilities/classes/class.ilUtil.php";
4316  $export_dir = ilUtil::getDataDir()."/svy_data"."/svy_".$this->getId()."/export";
4317 
4318  return $export_dir;
4319  }
4320 
4324  function getExportFiles($dir)
4325  {
4326  // quit if import dir not available
4327  if (!@is_dir($dir) or
4328  !is_writeable($dir))
4329  {
4330  return array();
4331  }
4332 
4333  // open directory
4334  $dir = dir($dir);
4335 
4336  // initialize array
4337  $file = array();
4338 
4339  // get files and save the in the array
4340  while ($entry = $dir->read())
4341  {
4342  if ($entry != "." && $entry != ".." && ereg("^[0-9]{10}_{2}[0-9]+_{2}(svy_)*[0-9]+\.[a-z]{1,3}\$", $entry))
4343  {
4344  $file[] = $entry;
4345  }
4346  }
4347 
4348  // close import directory
4349  $dir->close();
4350  // sort files
4351  sort ($file);
4352  reset ($file);
4353 
4354  return $file;
4355  }
4356 
4363  {
4364  include_once "./Services/Utilities/classes/class.ilUtil.php";
4365  $svy_data_dir = ilUtil::getDataDir()."/svy_data";
4366  ilUtil::makeDir($svy_data_dir);
4367 
4368  if(!is_writable($svy_data_dir))
4369  {
4370  $this->ilias->raiseError("Survey Data Directory (".$svy_data_dir
4371  .") not writeable.",$this->ilias->error_obj->FATAL);
4372  }
4373 
4374  // create test directory (data_dir/svy_data/svy_<id>)
4375  $svy_dir = $svy_data_dir."/svy_".$this->getId();
4376  ilUtil::makeDir($svy_dir);
4377  if(!@is_dir($svy_dir))
4378  {
4379  $this->ilias->raiseError("Creation of Survey Directory failed.",$this->ilias->error_obj->FATAL);
4380  }
4381 
4382  // create import subdirectory (data_dir/svy_data/svy_<id>/import)
4383  $import_dir = $svy_dir."/import";
4384  ilUtil::makeDir($import_dir);
4385  if(!@is_dir($import_dir))
4386  {
4387  $this->ilias->raiseError("Creation of Import Directory failed.",$this->ilias->error_obj->FATAL);
4388  }
4389  }
4390 
4395  {
4396  include_once "./Services/Utilities/classes/class.ilUtil.php";
4397  $import_dir = ilUtil::getDataDir()."/svy_data".
4398  "/svy_".$this->getId()."/import";
4399  if (!is_dir($import_dir))
4400  {
4401  ilUtil::makeDirParents($import_dir);
4402  }
4403  if(@is_dir($import_dir))
4404  {
4405  return $import_dir;
4406  }
4407  else
4408  {
4409  return false;
4410  }
4411  }
4412 
4413  function saveHeading($heading = "", $insertbefore)
4414  {
4415  global $ilDB;
4416  if ($heading)
4417  {
4418  $affectedRows = $ilDB->manipulateF("UPDATE svy_svy_qst SET heading=%s WHERE survey_fi=%s AND question_fi=%s",
4419  array('text','integer','integer'),
4420  array($heading, $this->getSurveyId(), $insertbefore)
4421  );
4422  }
4423  else
4424  {
4425  $affectedRows = $ilDB->manipulateF("UPDATE svy_svy_qst SET heading=%s WHERE survey_fi=%s AND question_fi=%s",
4426  array('text','integer','integer'),
4427  array(NULL, $this->getSurveyId(), $insertbefore)
4428  );
4429  }
4430  }
4431 
4432  function isAnonymousKey($key)
4433  {
4434  global $ilDB;
4435 
4436  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_anonymous WHERE survey_key = %s AND survey_fi = %s",
4437  array('text','integer'),
4438  array($key, $this->getSurveyId())
4439  );
4440  return ($result->numRows() == 1) ? true : false;
4441  }
4442 
4443  function getUserSurveyCode($user_id)
4444  {
4445  global $ilDB;
4446 
4447  if (($user_id == ANONYMOUS_USER_ID) || (($this->isAccessibleWithoutCode() && $this->isAllowedToTakeMultipleSurveys()))) return "";
4448  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_finished WHERE survey_fi = %s AND user_fi = %s",
4449  array('integer','integer'),
4450  array($this->getSurveyId(), $user_id)
4451  );
4452  if ($result->numRows() == 1)
4453  {
4454  $row = $ilDB->fetchAssoc($result);
4455  return $row["anonymous_id"];
4456  }
4457  else
4458  {
4459  return "";
4460  }
4461  }
4462 
4464  {
4465  global $ilDB;
4466 
4467  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE anonymous_id = %s AND survey_fi = %s",
4468  array('text','integer'),
4469  array($key, $this->getSurveyId())
4470  );
4471  return ($result->numRows() == 1) ? true : false;
4472  }
4473 
4474  function checkSurveyCode($code)
4475  {
4476  if ($this->isAnonymousKey($code))
4477  {
4478  if ($this->isSurveyStarted("", $code) == 1)
4479  {
4480  return false;
4481  }
4482  else
4483  {
4484  return true;
4485  }
4486  }
4487  else
4488  {
4489  return false;
4490  }
4491  }
4492 
4500  {
4501  global $ilDB;
4502 
4503  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_anonymous WHERE survey_fi = %s AND user_key IS NULL",
4504  array('integer'),
4505  array($this->getSurveyId())
4506  );
4507  return $result->numRows();
4508  }
4509 
4517  function getSurveyCodesForExport($a_array)
4518  {
4519  global $ilDB, $ilUser;
4520 
4521  $result = $ilDB->queryF("SELECT svy_anonymous.*, svy_finished.state FROM svy_anonymous ".
4522  "LEFT JOIN svy_finished ON svy_anonymous.survey_key = svy_finished.anonymous_id ".
4523  "WHERE svy_anonymous.survey_fi = %s AND svy_anonymous.user_key IS NULL",
4524  array('integer'),
4525  array($this->getSurveyId())
4526  );
4527  $export = "";
4528  $default_lang = $ilUser->getPref("survey_code_language");
4529  $lang = (strlen($default_lang)) ? "&lang=" . $default_lang : "";
4530  while ($row = $ilDB->fetchAssoc($result))
4531  {
4532  if (in_array($row["survey_key"], $a_array) || (count($a_array) == 0))
4533  {
4534  $export .= $row["survey_key"] . ",";
4535 
4536  // No relative (today, tomorrow...) dates in export.
4537  $date = new ilDate($row['tstamp'],IL_CAL_UNIX);
4538  $created = $date->get(IL_CAL_DATE);
4539  $export .= "$created,";
4540  if ($this->isSurveyCodeUsed($row["survey_key"]))
4541  {
4542  $export .= "1,";
4543  }
4544  else
4545  {
4546  $export .= "0,";
4547  }
4548  $url = ILIAS_HTTP_PATH."/goto.php?cmd=infoScreen&target=svy_".$this->getRefId() . "&client_id=" . CLIENT_ID . "&accesscode=".$row["survey_key"].$lang;
4549  $export .= $url . "\n";
4550  }
4551  }
4552  return $export;
4553  }
4554 
4562  public function &getSurveyCodesTableData($lang = "en")
4563  {
4564  global $ilDB;
4565 
4566  if (strlen($lang) == 0) $lang = "en";
4567 
4568  $order = "ORDER BY tstamp, survey_key ASC";
4569  $codes = array();
4570  $result = $ilDB->queryF("SELECT svy_anonymous.anonymous_id, svy_anonymous.survey_key, svy_anonymous.survey_fi, ".
4571  "svy_anonymous.tstamp, svy_finished.state FROM svy_anonymous LEFT JOIN svy_finished ".
4572  "ON svy_anonymous.survey_key = svy_finished.anonymous_id WHERE svy_anonymous.survey_fi = %s ".
4573  "AND svy_anonymous.user_key IS NULL $order",
4574  array('integer'),
4575  array($this->getSurveyId())
4576  );
4577  if ($result->numRows() > 0)
4578  {
4579  while ($row = $ilDB->fetchAssoc($result))
4580  {
4581  $created = ilDatePresentation::formatDate(new ilDateTime($row["tstamp"],IL_CAL_UNIX));
4582  $url = "";
4583 
4584  $state = 0;
4585  if ($this->isSurveyCodeUsed($row["survey_key"]))
4586  {
4587  $state = 1;
4588  }
4589  else
4590  {
4591  $addlang = "";
4592  if (strlen($lang))
4593  {
4594  $addlang = "&amp;lang=$lang";
4595  }
4596  $href = ILIAS_HTTP_PATH."/goto.php?cmd=infoScreen&target=svy_".$this->getRefId() . "&amp;client_id=" . CLIENT_ID . "&amp;accesscode=".$row["survey_key"].$addlang;
4597  $url = $this->lng->txt("survey_code_url_name");
4598  }
4599  array_push($codes, array('code' => $row["survey_key"], 'date' => $created, 'used' => $state, 'url' => $url, 'href' => $href));
4600  }
4601  }
4602  return $codes;
4603  }
4604 
4605  function isSurveyCodeUsed($code)
4606  {
4607  global $ilDB;
4608  $result = $ilDB->queryF("SELECT finished_id FROM svy_finished WHERE survey_fi = %s AND anonymous_id = %s",
4609  array('integer','text'),
4610  array($this->getSurveyId(), $code)
4611  );
4612  return ($result->numRows() > 0) ? true : false;
4613  }
4614 
4615  function isSurveyCodeUnique($code)
4616  {
4617  global $ilDB;
4618  $result = $ilDB->queryF("SELECT anonymous_id FROM svy_anonymous WHERE survey_fi = %s AND survey_key = %s",
4619  array('integer','text'),
4620  array($this->getSurveyId(), $code)
4621  );
4622  return ($result->numRows() > 0) ? false : true;
4623  }
4624 
4625  function createSurveyCodes($nrOfCodes)
4626  {
4627  global $ilDB;
4628  for ($i = 0; $i < $nrOfCodes; $i++)
4629  {
4630  $anonymize_key = $this->createNewAccessCode();
4631  $next_id = $ilDB->nextId('svy_anonymous');
4632  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, tstamp) ".
4633  "VALUES (%s, %s, %s, %s)",
4634  array('integer','text','integer','integer'),
4635  array($next_id, $anonymize_key, $this->getSurveyId(), time())
4636  );
4637  }
4638  }
4639 
4641  {
4642  global $ilDB;
4643  foreach ($data as $dataset)
4644  {
4645  $anonymize_key = $this->createNewAccessCode();
4646  $next_id = $ilDB->nextId('svy_anonymous');
4647  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, externaldata, tstamp) ".
4648  "VALUES (%s, %s, %s, %s, %s)",
4649  array('integer','text','integer','text','integer'),
4650  array($next_id, $anonymize_key, $this->getSurveyId(), serialize($dataset), time())
4651  );
4652  }
4653  }
4654 
4655  function sendCodes($not_sent, $subject, $message, $lang = "en")
4656  {
4657  /*
4658  * 0 = all
4659  * 1 = not sent
4660  * 2 = finished
4661  * 3 = not finished
4662  */
4663  $check_finished = ($not_sent > 1);
4664 
4665  include_once "./Services/Mail/classes/class.ilMail.php";
4666  $user_id = $this->getOwner();
4667  $mail = new ilMail($user_id);
4668  $recipients = $this->getExternalCodeRecipients($check_finished);
4669  foreach ($recipients as $data)
4670  {
4671  if($data['email'] && $data['code'])
4672  {
4673  $do_send = false;
4674  switch ((int)$not_sent)
4675  {
4676  case 1:
4677  $do_send = !(bool)$data['sent'];
4678  break;
4679 
4680  case 2:
4681  $do_send = $data['finished'];
4682  break;
4683 
4684  case 3:
4685  $do_send = !$data['finished'];
4686  break;
4687 
4688  default:
4689  $do_send = true;
4690  break;
4691  }
4692  if ($do_send)
4693  {
4694  // build text
4695  $messagetext = $message;
4696  $url = ILIAS_HTTP_PATH."/goto.php?cmd=infoScreen&target=svy_".$this->getRefId() . "&client_id=" . CLIENT_ID . "&accesscode=".$data["code"]."&lang=".$lang;
4697  $messagetext = str_replace('[url]', "<" . $url . ">", $messagetext);
4698  foreach ($data as $key => $value)
4699  {
4700  $messagetext = str_replace('[' . $key . ']', $value, $messagetext);
4701  }
4702 
4703  // send mail
4704  $mail->sendMail(
4705  $data['email'], // to
4706  "", // cc
4707  "", // bcc
4708  $subject, // subject
4709  $messagetext, // message
4710  array(), // attachments
4711  array('normal') // type
4712  );
4713  }
4714  }
4715  }
4716 
4717  global $ilDB;
4718  $ilDB->manipulateF("UPDATE svy_anonymous SET sent = %s WHERE survey_fi = %s AND externaldata IS NOT NULL",
4719  array('integer','integer'),
4720  array(1, $this->getSurveyId())
4721  );
4722  }
4723 
4724  function getExternalCodeRecipients($a_check_finished = false)
4725  {
4726  global $ilDB;
4727  $result = $ilDB->queryF("SELECT survey_key code, externaldata, sent FROM svy_anonymous WHERE survey_fi = %s AND externaldata IS NOT NULL",
4728  array('integer'),
4729  array($this->getSurveyId())
4730  );
4731  $res = array();
4732  while ($row = $ilDB->fetchAssoc($result))
4733  {
4734  $externaldata = unserialize($row['externaldata']);
4735  $externaldata['code'] = $row['code'];
4736  $externaldata['sent'] = $row['sent'];
4737 
4738  if($a_check_finished)
4739  {
4740  $externaldata['finished'] = $this->isSurveyCodeUsed($row['code']);
4741  }
4742 
4743  array_push($res, $externaldata);
4744  }
4745  return $res;
4746  }
4747 
4753  function deleteSurveyCode($survey_code)
4754  {
4755  global $ilDB;
4756 
4757  if (strlen($survey_code) > 0)
4758  {
4759  $affectedRows = $ilDB->manipulateF("DELETE FROM svy_anonymous WHERE survey_fi = %s AND survey_key = %s",
4760  array('integer', 'text'),
4761  array($this->getSurveyId(), $survey_code)
4762  );
4763  }
4764  }
4765 
4772  function getUserAccessCode($user_id)
4773  {
4774  global $ilDB;
4775  $access_code = "";
4776  $result = $ilDB->queryF("SELECT survey_key FROM svy_anonymous WHERE survey_fi = %s AND user_key = %s",
4777  array('integer','text'),
4778  array($this->getSurveyId(), md5($user_id))
4779  );
4780  if ($result->numRows())
4781  {
4782  $row = $ilDB->fetchAssoc($result);
4783  $access_code = $row["survey_key"];
4784  }
4785  return $access_code;
4786  }
4787 
4794  function saveUserAccessCode($user_id, $access_code)
4795  {
4796  global $ilDB;
4797  $next_id = $ilDB->nextId('svy_anonymous');
4798  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_anonymous (anonymous_id, survey_key, survey_fi, user_key, tstamp) ".
4799  "VALUES (%s, %s, %s, %s, %s)",
4800  array('integer','text', 'integer', 'text', 'integer'),
4801  array($next_id, $access_code, $this->getSurveyId(), md5($user_id), time())
4802  );
4803  }
4804 
4811  {
4812  // create a 5 character code
4813  $codestring = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
4814  mt_srand();
4815  $code = "";
4816  for ($i = 1; $i <=5; $i++)
4817  {
4818  $index = mt_rand(0, strlen($codestring)-1);
4819  $code .= substr($codestring, $index, 1);
4820  }
4821  // verify it against the database
4822  while (!$this->isSurveyCodeUnique($code))
4823  {
4824  $code = $this->createNewAccessCode();
4825  }
4826  return $code;
4827  }
4828 
4829 
4840  function &processCSVRow($row, $quoteAll = FALSE, $separator = ";")
4841  {
4842  $resultarray = array();
4843  foreach ($row as $rowindex => $entry)
4844  {
4845  if(is_array($entry))
4846  {
4847  $entry = implode("/", $entry);
4848  }
4849  $surround = FALSE;
4850  if ($quoteAll)
4851  {
4852  $surround = TRUE;
4853  }
4854  if (strpos($entry, "\"") !== FALSE)
4855  {
4856  $entry = str_replace("\"", "\"\"", $entry);
4857  $surround = TRUE;
4858  }
4859  if (strpos($entry, $separator) !== FALSE)
4860  {
4861  $surround = TRUE;
4862  }
4863  // replace all CR LF with LF (for Excel for Windows compatibility
4864  $entry = str_replace(chr(13).chr(10), chr(10), $entry);
4865  if ($surround)
4866  {
4867  $resultarray[$rowindex] = utf8_decode("\"" . $entry . "\"");
4868  }
4869  else
4870  {
4871  $resultarray[$rowindex] = utf8_decode($entry);
4872  }
4873  }
4874  return $resultarray;
4875  }
4876 
4877  function _getLastAccess($finished_id)
4878  {
4879  global $ilDB;
4880 
4881  $result = $ilDB->queryF("SELECT tstamp FROM svy_answer WHERE active_fi = %s ORDER BY tstamp DESC",
4882  array('integer'),
4883  array($finished_id)
4884  );
4885  if ($result->numRows())
4886  {
4887  $row = $ilDB->fetchAssoc($result);
4888  return $row["tstamp"];
4889  }
4890  else
4891  {
4892  $result = $ilDB->queryF("SELECT tstamp FROM svy_finished WHERE finished_id = %s",
4893  array('integer'),
4894  array($finished_id)
4895  );
4896  if ($result->numRows())
4897  {
4898  $row = $ilDB->fetchAssoc($result);
4899  return $row["tstamp"];
4900  }
4901  }
4902  return "";
4903  }
4904 
4911  function prepareTextareaOutput($txt_output)
4912  {
4913  include_once "./Services/Utilities/classes/class.ilUtil.php";
4914  return ilUtil::prepareTextareaOutput($txt_output, $prepare_for_latex_output);
4915  }
4916 
4924  function isHTML($a_text)
4925  {
4926  if (preg_match("/<[^>]*?>/", $a_text))
4927  {
4928  return TRUE;
4929  }
4930  else
4931  {
4932  return FALSE;
4933  }
4934  }
4935 
4944  function addMaterialTag(&$a_xml_writer, $a_material, $close_material_tag = TRUE, $add_mobs = TRUE, $attribs = NULL)
4945  {
4946  include_once "./Services/RTE/classes/class.ilRTE.php";
4947  include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php");
4948 
4949  $a_xml_writer->xmlStartTag("material", $attribs);
4950  $attrs = array(
4951  "type" => "text/plain"
4952  );
4953  if ($this->isHTML($a_material))
4954  {
4955  $attrs["type"] = "text/xhtml";
4956  }
4957  $mattext = ilRTE::_replaceMediaObjectImageSrc($a_material, 0);
4958  $a_xml_writer->xmlElement("mattext", $attrs, $mattext);
4959 
4960  if ($add_mobs)
4961  {
4962  $mobs = ilObjMediaObject::_getMobsOfObject("svy:html", $this->getId());
4963  foreach ($mobs as $mob)
4964  {
4965  $mob_id = "il_" . IL_INST_ID . "_mob_" . $mob;
4966  if (strpos($mattext, $mob_id) !== FALSE)
4967  {
4968  $mob_obj =& new ilObjMediaObject($mob);
4969  $imgattrs = array(
4970  "label" => $mob_id,
4971  "uri" => "objects/" . "il_" . IL_INST_ID . "_mob_" . $mob . "/" . $mob_obj->getTitle()
4972  );
4973  $a_xml_writer->xmlElement("matimage", $imgattrs, NULL);
4974  }
4975  }
4976  }
4977  if ($close_material_tag) $a_xml_writer->xmlEndTag("material");
4978  }
4979 
4989  {
4990  if ($this->getAnonymize() != ANONYMIZE_OFF)
4991  {
4992  if ($this->surveyCodeSecurity == FALSE)
4993  {
4994  return TRUE;
4995  }
4996  }
4997  return FALSE;
4998  }
4999 
5007  function processPrintoutput2FO($print_output)
5008  {
5009  global $ilLog;
5010 
5011  if (extension_loaded("tidy"))
5012  {
5013  $config = array(
5014  "indent" => false,
5015  "output-xml" => true,
5016  "numeric-entities" => true
5017  );
5018  $tidy = new tidy();
5019  $tidy->parseString($print_output, $config, 'utf8');
5020  $tidy->cleanRepair();
5021  $print_output = tidy_get_output($tidy);
5022  $print_output = preg_replace("/^.*?(<html)/", "\\1", $print_output);
5023  }
5024  else
5025  {
5026  $print_output = str_replace("&nbsp;", "&#160;", $print_output);
5027  $print_output = str_replace("&otimes;", "X", $print_output);
5028  }
5029  $xsl = file_get_contents("./Modules/Survey/xml/question2fo.xsl");
5030 
5031  // additional font support
5032  $xsl = str_replace(
5033  'font-family="Helvetica, unifont"',
5034  'font-family="'.$GLOBALS['ilSetting']->get('rpc_pdf_font','Helvetica, unifont').'"',
5035  $xsl
5036  );
5037 
5038  $args = array( '/_xml' => $print_output, '/_xsl' => $xsl );
5039  $xh = xslt_create();
5040  $params = array();
5041  $output = xslt_process($xh, "arg:/_xml", "arg:/_xsl", NULL, $args, $params);
5042  xslt_error($xh);
5043  xslt_free($xh);
5044  $ilLog->write($output);
5045  return $output;
5046  }
5047 
5054  function deliverPDFfromFO($fo)
5055  {
5056  global $ilLog;
5057 
5058  include_once "./Services/Utilities/classes/class.ilUtil.php";
5059  $fo_file = ilUtil::ilTempnam() . ".fo";
5060  $fp = fopen($fo_file, "w"); fwrite($fp, $fo); fclose($fp);
5061 
5062  include_once './Services/WebServices/RPC/classes/class.ilRpcClientFactory.php';
5063  try
5064  {
5065  $pdf_base64 = ilRpcClientFactory::factory('RPCTransformationHandler')->ilFO2PDF($fo);
5066  ilUtil::deliverData($pdf_base64->scalar, ilUtil::getASCIIFilename($this->getTitle()) . ".pdf", "application/pdf");
5067  return true;
5068  }
5069  catch(XML_RPC2_FaultException $e)
5070  {
5071  $ilLog->write(__METHOD__.': '.$e->getMessage());
5072  return false;
5073  }
5074  catch(Exception $e)
5075  {
5076  $ilLog->write(__METHOD__.': '.$e->getMessage());
5077  return false;
5078  }
5079 
5080  /*
5081  include_once "./Services/Transformation/classes/class.ilFO2PDF.php";
5082  $fo2pdf = new ilFO2PDF();
5083  $fo2pdf->setFOString($fo);
5084  $result = $fo2pdf->send();
5085  ilUtil::deliverData($result, ilUtil::getASCIIFilename($this->getTitle()) . ".pdf", "application/pdf");
5086  */
5087  }
5088 
5089  function _checkCondition($a_svy_id,$a_operator,$a_value,$a_usr_id = 0)
5090  {
5091  global $ilUser;
5092 
5093  $a_usr_id = $a_usr_id ? $a_usr_id : $ilUser->getId();
5094 
5095  switch($a_operator)
5096  {
5097  case 'finished':
5098  //if (ilExerciseMembers::_lookupStatus($a_exc_id, $ilias->account->getId()) == "passed")
5099  include_once("./Modules/Survey/classes/class.ilObjSurveyAccess.php");
5100  if (ilObjSurveyAccess::_lookupFinished($a_svy_id, $a_usr_id))
5101  {
5102  return true;
5103  }
5104  else
5105  {
5106  return false;
5107  }
5108  break;
5109 
5110  default:
5111  return true;
5112  }
5113  return true;
5114  }
5115 
5122  function isPluginActive($a_pname)
5123  {
5124  global $ilPluginAdmin;
5125  if ($ilPluginAdmin->isActive(IL_COMP_MODULE, "SurveyQuestionPool", "svyq", $a_pname))
5126  {
5127  return TRUE;
5128  }
5129  else
5130  {
5131  return FALSE;
5132  }
5133  }
5134 
5140  public function setSurveyId($survey_id)
5141  {
5142  $this->survey_id = $survey_id;
5143  }
5144 
5151  public function &getUserData($ids)
5152  {
5153  global $ilDB;
5154 
5155  if (!is_array($ids) || count($ids) ==0) return array();
5156 
5157  $result = $ilDB->query("SELECT usr_id, login, lastname, firstname FROM usr_data WHERE " . $ilDB->in('usr_id', $ids, false, 'integer') . " ORDER BY login");
5158  $result_array = array();
5159  while ($row = $ilDB->fetchAssoc($result))
5160  {
5161  $result_array[$row["usr_id"]]= $row;
5162  }
5163  return $result_array;
5164  }
5165 
5166  function &getGroupData($ids)
5167  {
5168  if (!is_array($ids) || count($ids) ==0) return array();
5169  $result = array();
5170  foreach ($ids as $ref_id)
5171  {
5172  $obj_id = ilObject::_lookupObjId($ref_id);
5173  $result[$ref_id] = array("ref_id" => $ref_id, "title" => ilObject::_lookupTitle($obj_id), "description" => ilObject::_lookupDescription($obj_id));
5174  }
5175  return $result;
5176  }
5177 
5178  function &getRoleData($ids)
5179  {
5180  if (!is_array($ids) || count($ids) ==0) return array();
5181  $result = array();
5182  foreach ($ids as $obj_id)
5183  {
5184  $result[$obj_id] = array("obj_id" => $obj_id, "title" => ilObject::_lookupTitle($obj_id), "description" => ilObject::_lookupDescription($obj_id));
5185  }
5186  return $result;
5187  }
5188 
5190  {
5191  return $this->mailnotification;
5192  }
5193 
5194  function setMailNotification($a_notification)
5195  {
5196  $this->mailnotification = ($a_notification) ? true : false;
5197  }
5198 
5199  function getMailAddresses()
5200  {
5201  return $this->mailaddresses;
5202  }
5203 
5204  function setMailAddresses($a_addresses)
5205  {
5206  $this->mailaddresses = $a_addresses;
5207  }
5208 
5210  {
5212  }
5213 
5214  function setMailParticipantData($a_data)
5215  {
5216  $this->mailparticipantdata = $a_data;
5217  }
5218 
5219  public function getSurveyTimes()
5220  {
5221  global $ilDB;
5222 
5223  $result = $ilDB->queryF("SELECT * FROM svy_times, svy_finished WHERE svy_finished.survey_fi = %s",
5224  array('integer'),
5225  array($this->getId())
5226  );
5227  $times = array();;
5228  while ($row = $ilDB->fetchAssoc($result))
5229  {
5230  if (strlen($row['left_page']) && strlen($row['entered_page']))
5231  $times[$row['finished_fi']] += ($row['left_page']-$row['entered_page']);
5232  }
5233  return $times;
5234  }
5235 
5236  function setStartTime($finished_id, $first_question)
5237  {
5238  global $ilDB;
5239  $time = time();
5240  $_SESSION['svy_entered_page'] = $time;
5241  $affectedRows = $ilDB->manipulateF("INSERT INTO svy_times (finished_fi, entered_page, left_page, first_question) VALUES (%s, %s, %s, %s)",
5242  array('integer', 'integer', 'integer', 'integer'),
5243  array($finished_id, $time, NULL, $first_question)
5244  );
5245  }
5246 
5247  function setEndTime($finished_id)
5248  {
5249  global $ilDB;
5250  $time = time();
5251  $affectedRows = $ilDB->manipulateF("UPDATE svy_times SET left_page = %s WHERE finished_fi = %s AND entered_page = %s",
5252  array('integer', 'integer', 'integer'),
5253  array($time, $finished_id, $_SESSION['svy_entered_page'])
5254  );
5255  unset($_SESSION['svy_entered_page']);
5256  }
5257 
5258  function getWorkingtimeForParticipant($finished_id)
5259  {
5260  global $ilDB;
5261 
5262  $result = $ilDB->queryF("SELECT * FROM svy_times WHERE finished_fi = %s",
5263  array('integer'),
5264  array($finished_id)
5265  );
5266  $total = 0;
5267  while ($row = $ilDB->fetchAssoc($result))
5268  {
5269  if ($row['left_page'] > 0 && $row['entered_page'] > 0)
5270  $total += $row['left_page'] - $row['entered_page'];
5271  }
5272  return $total;
5273  }
5274 
5276  {
5277  $this->template_id = (int)$template_id;
5278  }
5279 
5280  function getTemplate()
5281  {
5282  return $this->template_id;
5283  }
5284 
5285  function updateOrder(array $a_order)
5286  {
5287  if(sizeof($this->questions) == sizeof($a_order))
5288  {
5289  $this->questions = array_flip($a_order);
5290  $this->saveQuestionsToDB();
5291  }
5292  }
5293 
5294  function getPoolUsage()
5295  {
5296  return $this->pool_usage;
5297  }
5298 
5299  function setPoolUsage($a_value)
5300  {
5301  $this->pool_usage = (bool)$a_value;
5302  }
5303 
5309  function isPoolActive()
5310  {
5311  $use_pool = (bool)$this->getPoolUsage();
5312  $template_settings = $this->getTemplate();
5313  if($template_settings)
5314  {
5315  include_once "Services/Administration/classes/class.ilSettingsTemplate.php";
5316  $template_settings = new ilSettingsTemplate($template_settings);
5317  $template_settings = $template_settings->getSettings();
5318  $template_settings = $template_settings["use_pool"];
5319  if($template_settings && $template_settings["hide"])
5320  {
5321  $use_pool = (bool)$template_settings["value"];
5322  }
5323  }
5324  return $use_pool;
5325  }
5326 
5333  {
5334  if(!$template_id)
5335  {
5336  return;
5337  }
5338 
5339  include_once "Services/Administration/classes/class.ilSettingsTemplate.php";
5340  $template = new ilSettingsTemplate($template_id);
5341  $template_settings = $template->getSettings();
5342  if($template_settings)
5343  {
5344  if($template_settings["show_question_titles"] !== NULL)
5345  {
5346  if($template_settings["show_question_titles"]["value"])
5347  {
5348  $this->setShowQuestionTitles(true);
5349  }
5350  else
5351  {
5352  $this->setShowQuestionTitles(false);
5353  }
5354  }
5355 
5356  if($template_settings["use_pool"] !== NULL)
5357  {
5358  if($template_settings["use_pool"]["value"])
5359  {
5360  $this->setPoolUsage(true);
5361  }
5362  else
5363  {
5364  $this->setPoolUsage(false);
5365  }
5366  }
5367 
5368  if($template_settings["anonymization_options"]["value"])
5369  {
5370  $anon_map = array('personalized' => ANONYMIZE_OFF,
5371  'anonymize_with_code' => ANONYMIZE_ON,
5372  'anonymize_without_code' => ANONYMIZE_FREEACCESS);
5373  $this->setAnonymize($anon_map[$template_settings["anonymization_options"]["value"]]);
5374  }
5375 
5376  /* other settings: not needed here
5377  * - enabled_end_date
5378  * - enabled_start_date
5379  * - rte_switch
5380  */
5381  }
5382 
5383  $this->setTemplate($template_id);
5384  $this->saveToDb();
5385  }
5386 
5387  function setActivationStartDate($starting_time = NULL)
5388  {
5389  $this->activation_starting_time = $starting_time;
5390  }
5391 
5392  function setActivationEndDate($ending_time = NULL)
5393  {
5394  $this->activation_ending_time = $ending_time;
5395  }
5396 
5398  {
5399  return (strlen($this->activation_starting_time)) ? $this->activation_starting_time : NULL;
5400  }
5401 
5403  {
5404  return (strlen($this->activation_ending_time)) ? $this->activation_ending_time : NULL;
5405  }
5406 
5407 } // END class.ilObjSurvey
5408 
5409 ?>