diff --git a/Modules/Blog/classes/class.ilBlogDataSet.php b/Modules/Blog/classes/class.ilBlogDataSet.php
index 19999a7f60d032cf739be9a321322115f8cf2c76..54d33bf5f3c4b7545a27e4e2ac938cd58724ae9d 100644
--- a/Modules/Blog/classes/class.ilBlogDataSet.php
+++ b/Modules/Blog/classes/class.ilBlogDataSet.php
@@ -5,7 +5,7 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php");
/**
* Blog Data set class
- *
+ *
* This class implements the following entities:
* - blog: object data
* - blog_posting: data from table il_blog_posting
@@ -16,376 +16,344 @@ include_once("./Services/DataSet/classes/class.ilDataSet.php");
*/
class ilBlogDataSet extends ilDataSet
{
- protected $current_blog;
-
- static public $style_map = array();
-
- /**
- * Get supported versions
- */
- public function getSupportedVersions()
- {
- return array("4.3.0", "5.0.0", "5.3.0");
- }
-
- /**
- * Get xml namespace
- */
- function getXmlNamespace($a_entity, $a_schema_version)
- {
- return "http://www.ilias.de/xml/Modules/Blog/".$a_entity;
- }
-
- /**
- * Get field types for entity
- */
- protected function getTypes($a_entity, $a_version)
- {
- if ($a_entity == "blog")
- {
- switch ($a_version)
- {
- case "4.3.0":
- return array(
- "Id" => "integer",
- "Title" => "text",
- "Description" => "text",
- "Notes" => "integer",
- "BgColor" => "text",
- "FontColor" => "text",
- "Img" => "text",
- "Ppic" => "integer",
- "RssActive" => "integer",
- "Approval" => "integer",
- "Dir" => "directory"
- );
-
- case "5.0.0":
- return array(
- "Id" => "integer",
- "Title" => "text",
- "Description" => "text",
- "Notes" => "integer",
- "BgColor" => "text",
- "FontColor" => "text",
- "Img" => "text",
- "Ppic" => "integer",
- "RssActive" => "integer",
- "Approval" => "integer",
- "Dir" => "directory",
- "AbsShorten" => "integer",
- "AbsShortenLen" => "integer",
- "AbsImage" => "integer",
- "AbsImgWidth" => "integer",
- "AbsImgHeight" => "integer",
- "NavMode" => "integer",
- "NavListPost" => "integer",
- "NavListMon" => "integer",
- "Keywords" => "integer",
- "Authors" => "integer",
- "NavOrder" => "text",
- "OvPost" => "integer",
- "Style" => "integer"
- );
+ protected $current_blog;
+
+ public static $style_map = array();
+
+ /**
+ * Get supported versions
+ */
+ public function getSupportedVersions()
+ {
+ return array("4.3.0", "5.0.0", "5.3.0");
+ }
+
+ /**
+ * Get xml namespace
+ */
+ public function getXmlNamespace($a_entity, $a_schema_version)
+ {
+ return "http://www.ilias.de/xml/Modules/Blog/" . $a_entity;
+ }
+
+ /**
+ * Get field types for entity
+ */
+ protected function getTypes($a_entity, $a_version)
+ {
+ if ($a_entity == "blog") {
+ switch ($a_version) {
+ case "4.3.0":
+ return array(
+ "Id" => "integer",
+ "Title" => "text",
+ "Description" => "text",
+ "Notes" => "integer",
+ "BgColor" => "text",
+ "FontColor" => "text",
+ "Img" => "text",
+ "Ppic" => "integer",
+ "RssActive" => "integer",
+ "Approval" => "integer",
+ "Dir" => "directory"
+ );
+
+ case "5.0.0":
+ return array(
+ "Id" => "integer",
+ "Title" => "text",
+ "Description" => "text",
+ "Notes" => "integer",
+ "BgColor" => "text",
+ "FontColor" => "text",
+ "Img" => "text",
+ "Ppic" => "integer",
+ "RssActive" => "integer",
+ "Approval" => "integer",
+ "Dir" => "directory",
+ "AbsShorten" => "integer",
+ "AbsShortenLen" => "integer",
+ "AbsImage" => "integer",
+ "AbsImgWidth" => "integer",
+ "AbsImgHeight" => "integer",
+ "NavMode" => "integer",
+ "NavListPost" => "integer",
+ "NavListMon" => "integer",
+ "Keywords" => "integer",
+ "Authors" => "integer",
+ "NavOrder" => "text",
+ "OvPost" => "integer",
+ "Style" => "integer"
+ );
- case "5.3.0":
- return array(
- "Id" => "integer",
- "Title" => "text",
- "Description" => "text",
- "Notes" => "integer",
- "BgColor" => "text",
- "FontColor" => "text",
- "Img" => "text",
- "Ppic" => "integer",
- "RssActive" => "integer",
- "Approval" => "integer",
- "Dir" => "directory",
- "AbsShorten" => "integer",
- "AbsShortenLen" => "integer",
- "AbsImage" => "integer",
- "AbsImgWidth" => "integer",
- "AbsImgHeight" => "integer",
- "NavMode" => "integer",
- "NavListMonWithPost" => "integer",
- "NavListMon" => "integer",
- "Keywords" => "integer",
- "Authors" => "integer",
- "NavOrder" => "text",
- "OvPost" => "integer",
- "Style" => "integer"
- );
+ case "5.3.0":
+ return array(
+ "Id" => "integer",
+ "Title" => "text",
+ "Description" => "text",
+ "Notes" => "integer",
+ "BgColor" => "text",
+ "FontColor" => "text",
+ "Img" => "text",
+ "Ppic" => "integer",
+ "RssActive" => "integer",
+ "Approval" => "integer",
+ "Dir" => "directory",
+ "AbsShorten" => "integer",
+ "AbsShortenLen" => "integer",
+ "AbsImage" => "integer",
+ "AbsImgWidth" => "integer",
+ "AbsImgHeight" => "integer",
+ "NavMode" => "integer",
+ "NavListMonWithPost" => "integer",
+ "NavListMon" => "integer",
+ "Keywords" => "integer",
+ "Authors" => "integer",
+ "NavOrder" => "text",
+ "OvPost" => "integer",
+ "Style" => "integer"
+ );
- }
- }
-
- if ($a_entity == "blog_posting")
- {
- switch ($a_version)
- {
- case "4.3.0":
- case "5.0.0":
- case "5.3.0":
- return array(
- "Id" => "integer",
- "BlogId" => "integer",
- "Title" => "integer",
- "Created" => "text",
- "Author" => "text",
- "Approved" => "integer"
- );
- }
- }
- }
+ }
+ }
+
+ if ($a_entity == "blog_posting") {
+ switch ($a_version) {
+ case "4.3.0":
+ case "5.0.0":
+ case "5.3.0":
+ return array(
+ "Id" => "integer",
+ "BlogId" => "integer",
+ "Title" => "integer",
+ "Created" => "text",
+ "Author" => "text",
+ "Approved" => "integer"
+ );
+ }
+ }
+ }
- /**
- * Read data
- *
- * @param
- * @return
- */
- function readData($a_entity, $a_version, $a_ids, $a_field = "")
- {
- $ilDB = $this->db;
+ /**
+ * Read data
+ *
+ * @param
+ * @return
+ */
+ public function readData($a_entity, $a_version, $a_ids, $a_field = "")
+ {
+ $ilDB = $this->db;
- if (!is_array($a_ids))
- {
- $a_ids = array($a_ids);
- }
-
- if ($a_entity == "blog")
- {
- switch ($a_version)
- {
- case "4.3.0":
- $this->getDirectDataFromQuery("SELECT bl.id,od.title,od.description,".
- "bl.notes,bl.bg_color,bl.font_color,bl.img,bl.ppic,bl.rss_active,bl.approval".
- " FROM il_blog bl".
- " JOIN object_data od ON (od.obj_id = bl.id)".
- " WHERE ".$ilDB->in("bl.id", $a_ids, false, "integer").
- " AND od.type = ".$ilDB->quote("blog", "text"));
- break;
-
- case "5.0.0":
- $this->getDirectDataFromQuery("SELECT bl.id,od.title,od.description,".
- "bl.bg_color,bl.font_color,bl.img,bl.ppic,bl.rss_active,bl.approval,".
- "bl.abs_shorten,bl.abs_shorten_len,bl.abs_image,bl.abs_img_width,bl.abs_img_height,".
- "bl.nav_mode,bl.nav_list_post,bl.nav_list_mon,bl.keywords,bl.authors,bl.nav_order,".
- "bl.ov_post".
- " FROM il_blog bl".
- " JOIN object_data od ON (od.obj_id = bl.id)".
- " WHERE ".$ilDB->in("bl.id", $a_ids, false, "integer").
- " AND od.type = ".$ilDB->quote("blog", "text"));
- break;
+ if (!is_array($a_ids)) {
+ $a_ids = array($a_ids);
+ }
+
+ if ($a_entity == "blog") {
+ switch ($a_version) {
+ case "4.3.0":
+ $this->getDirectDataFromQuery("SELECT bl.id,od.title,od.description," .
+ "bl.notes,bl.bg_color,bl.font_color,bl.img,bl.ppic,bl.rss_active,bl.approval" .
+ " FROM il_blog bl" .
+ " JOIN object_data od ON (od.obj_id = bl.id)" .
+ " WHERE " . $ilDB->in("bl.id", $a_ids, false, "integer") .
+ " AND od.type = " . $ilDB->quote("blog", "text"));
+ break;
+
+ case "5.0.0":
+ $this->getDirectDataFromQuery("SELECT bl.id,od.title,od.description," .
+ "bl.bg_color,bl.font_color,bl.img,bl.ppic,bl.rss_active,bl.approval," .
+ "bl.abs_shorten,bl.abs_shorten_len,bl.abs_image,bl.abs_img_width,bl.abs_img_height," .
+ "bl.nav_mode,bl.nav_list_post,bl.nav_list_mon,bl.keywords,bl.authors,bl.nav_order," .
+ "bl.ov_post" .
+ " FROM il_blog bl" .
+ " JOIN object_data od ON (od.obj_id = bl.id)" .
+ " WHERE " . $ilDB->in("bl.id", $a_ids, false, "integer") .
+ " AND od.type = " . $ilDB->quote("blog", "text"));
+ break;
- case "5.3.0":
- $this->getDirectDataFromQuery("SELECT bl.id,od.title,od.description,".
- "bl.bg_color,bl.font_color,bl.img,bl.ppic,bl.rss_active,bl.approval,".
- "bl.abs_shorten,bl.abs_shorten_len,bl.abs_image,bl.abs_img_width,bl.abs_img_height,".
- "bl.nav_mode,bl.nav_list_mon_with_post,bl.nav_list_mon,bl.keywords,bl.authors,bl.nav_order,".
- "bl.ov_post".
- " FROM il_blog bl".
- " JOIN object_data od ON (od.obj_id = bl.id)".
- " WHERE ".$ilDB->in("bl.id", $a_ids, false, "integer").
- " AND od.type = ".$ilDB->quote("blog", "text"));
- break;
- }
- }
-
- if ($a_entity == "blog_posting")
- {
- switch ($a_version)
- {
- case "4.3.0":
- case "5.0.0":
- case "5.3.0":
- $this->getDirectDataFromQuery("SELECT id,blog_id,title,created,author,approved".
- " FROM il_blog_posting WHERE ".
- $ilDB->in("blog_id", $a_ids, false, "integer"));
- foreach($this->data as $idx => $item)
- {
- // create full export id
- $this->data[$idx]["Author"] = $this->createObjectExportId("usr", $item["Author"]);
- }
- break;
- }
-
- // keywords
- include_once("./Modules/Blog/classes/class.ilBlogPosting.php");
- include_once("./Services/MetaData/classes/class.ilMDKeyword.php");
- foreach($this->data as $idx => $item)
- {
- $blog_id = ilBlogPosting::lookupBlogId($item["Id"]);
- $keywords = ilBlogPosting::getKeywords($blog_id, $item["Id"]);
- if($keywords)
- {
- foreach($keywords as $kidx => $keyword)
- {
- $this->data[$idx]["Keyword".$kidx] = $keyword;
- }
- }
- }
- }
- }
-
- /**
- * Determine the dependent sets of data
- */
- protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids)
- {
- switch ($a_entity)
- {
- case "blog":
- return array (
- "blog_posting" => array("ids" => $a_rec["Id"])
- );
- }
- return false;
- }
+ case "5.3.0":
+ $this->getDirectDataFromQuery("SELECT bl.id,od.title,od.description," .
+ "bl.bg_color,bl.font_color,bl.img,bl.ppic,bl.rss_active,bl.approval," .
+ "bl.abs_shorten,bl.abs_shorten_len,bl.abs_image,bl.abs_img_width,bl.abs_img_height," .
+ "bl.nav_mode,bl.nav_list_mon_with_post,bl.nav_list_mon,bl.keywords,bl.authors,bl.nav_order," .
+ "bl.ov_post" .
+ " FROM il_blog bl" .
+ " JOIN object_data od ON (od.obj_id = bl.id)" .
+ " WHERE " . $ilDB->in("bl.id", $a_ids, false, "integer") .
+ " AND od.type = " . $ilDB->quote("blog", "text"));
+ break;
+ }
+ }
+
+ if ($a_entity == "blog_posting") {
+ switch ($a_version) {
+ case "4.3.0":
+ case "5.0.0":
+ case "5.3.0":
+ $this->getDirectDataFromQuery("SELECT id,blog_id,title,created,author,approved" .
+ " FROM il_blog_posting WHERE " .
+ $ilDB->in("blog_id", $a_ids, false, "integer"));
+ foreach ($this->data as $idx => $item) {
+ // create full export id
+ $this->data[$idx]["Author"] = $this->createObjectExportId("usr", $item["Author"]);
+ }
+ break;
+ }
+
+ // keywords
+ include_once("./Modules/Blog/classes/class.ilBlogPosting.php");
+ include_once("./Services/MetaData/classes/class.ilMDKeyword.php");
+ foreach ($this->data as $idx => $item) {
+ $blog_id = ilBlogPosting::lookupBlogId($item["Id"]);
+ $keywords = ilBlogPosting::getKeywords($blog_id, $item["Id"]);
+ if ($keywords) {
+ foreach ($keywords as $kidx => $keyword) {
+ $this->data[$idx]["Keyword" . $kidx] = $keyword;
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Determine the dependent sets of data
+ */
+ protected function getDependencies($a_entity, $a_version, $a_rec, $a_ids)
+ {
+ switch ($a_entity) {
+ case "blog":
+ return array(
+ "blog_posting" => array("ids" => $a_rec["Id"])
+ );
+ }
+ return false;
+ }
- /**
- * Get xml record
- *
- * @param
- * @return
- */
- function getXmlRecord($a_entity, $a_version, $a_set)
- {
- if ($a_entity == "blog")
- {
- include_once("./Modules/Blog/classes/class.ilObjBlog.php");
- $dir = ilObjBlog::initStorage($a_set["Id"]);
- $a_set["Dir"] = $dir;
-
- include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php");
- $a_set["Style"] = ilObjStyleSheet::lookupObjectStyle($a_set["Id"]);
-
- // #14734
- include_once("./Services/Notes/classes/class.ilNote.php");
- $a_set["Notes"] = ilNote::commentsActivated($a_set["Id"], 0, "blog");
- }
+ /**
+ * Get xml record
+ *
+ * @param
+ * @return
+ */
+ public function getXmlRecord($a_entity, $a_version, $a_set)
+ {
+ if ($a_entity == "blog") {
+ include_once("./Modules/Blog/classes/class.ilObjBlog.php");
+ $dir = ilObjBlog::initStorage($a_set["Id"]);
+ $a_set["Dir"] = $dir;
+
+ include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php");
+ $a_set["Style"] = ilObjStyleSheet::lookupObjectStyle($a_set["Id"]);
+
+ // #14734
+ include_once("./Services/Notes/classes/class.ilNote.php");
+ $a_set["Notes"] = ilNote::commentsActivated($a_set["Id"], 0, "blog");
+ }
- return $a_set;
- }
-
- /**
- * Import record
- *
- * @param
- * @return
- */
- function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version)
- {
- switch ($a_entity)
- {
- case "blog":
- include_once("./Modules/Blog/classes/class.ilObjBlog.php");
-
- // container copy
- if($new_id = $a_mapping->getMapping("Services/Container", "objs", $a_rec["Id"]))
- {
- $newObj = ilObjectFactory::getInstanceByObjId($new_id, false);
- }
- else
- {
- $newObj = new ilObjBlog();
- $newObj->create();
- }
-
- $newObj->setTitle($a_rec["Title"]);
- $newObj->setDescription($a_rec["Description"]);
- $newObj->setNotesStatus($a_rec["Notes"]);
- $newObj->setBackgroundColor($a_rec["BgColor"]);
- $newObj->setFontColor($a_rec["FontColor"]);
- $newObj->setProfilePicture($a_rec["Ppic"]);
- $newObj->setRSS($a_rec["RssActive"]);
- $newObj->setApproval($a_rec["Approval"]);
- $newObj->setImage($a_rec["Img"]);
-
- $newObj->setAbstractShorten($a_rec["AbsShorten"]);
- $newObj->setAbstractShortenLength($a_rec["AbsShortenLen"]);
- $newObj->setAbstractImage($a_rec["AbsImage"]);
- $newObj->setAbstractImageWidth($a_rec["AbsImgWidth"]);
- $newObj->setAbstractImageHeight($a_rec["AbsImgHeight"]);
- $newObj->setNavMode($a_rec["NavMode"]);
- if ($a_rec["NavListMonWithPost"] == 0)
- {
- $newObj->setNavModeListMonthsWithPostings(3);
- }
- else
- {
- $newObj->setNavModeListMonthsWithPostings($a_rec["NavListMonWithPost"]);
- }
- //$newObj->setNavModeListPostings($a_rec["NavListPost"]);
- $newObj->setNavModeListMonths($a_rec["NavListMon"]);
- $newObj->setKeywords($a_rec["Keywords"]);
- $newObj->setAuthors($a_rec["Authors"]);
- $newObj->setOrder(trim($a_rec["NavOrder"])
- ? explode(";", $a_rec["NavOrder"])
- : null);
- $newObj->setOverviewPostings($a_rec["OvPost"]);
-
- $newObj->update();
-
- // handle image(s)
- if($a_rec["Img"])
- {
- $dir = str_replace("..", "", $a_rec["Dir"]);
- if ($dir != "" && $this->getImportDirectory() != "")
- {
- $source_dir = $this->getImportDirectory()."/".$dir;
- $target_dir = ilObjBlog::initStorage($newObj->getId());
- ilUtil::rCopy($source_dir, $target_dir);
- }
- }
+ return $a_set;
+ }
+
+ /**
+ * Import record
+ *
+ * @param
+ * @return
+ */
+ public function importRecord($a_entity, $a_types, $a_rec, $a_mapping, $a_schema_version)
+ {
+ switch ($a_entity) {
+ case "blog":
+ include_once("./Modules/Blog/classes/class.ilObjBlog.php");
+
+ // container copy
+ if ($new_id = $a_mapping->getMapping("Services/Container", "objs", $a_rec["Id"])) {
+ $newObj = ilObjectFactory::getInstanceByObjId($new_id, false);
+ } else {
+ $newObj = new ilObjBlog();
+ $newObj->create();
+ }
+
+ $newObj->setTitle($a_rec["Title"]);
+ $newObj->setDescription($a_rec["Description"]);
+ $newObj->setNotesStatus($a_rec["Notes"]);
+ $newObj->setBackgroundColor($a_rec["BgColor"]);
+ $newObj->setFontColor($a_rec["FontColor"]);
+ $newObj->setProfilePicture($a_rec["Ppic"]);
+ $newObj->setRSS($a_rec["RssActive"]);
+ $newObj->setApproval($a_rec["Approval"]);
+ $newObj->setImage($a_rec["Img"]);
+
+ $newObj->setAbstractShorten($a_rec["AbsShorten"]);
+ $newObj->setAbstractShortenLength($a_rec["AbsShortenLen"]);
+ $newObj->setAbstractImage($a_rec["AbsImage"]);
+ $newObj->setAbstractImageWidth($a_rec["AbsImgWidth"]);
+ $newObj->setAbstractImageHeight($a_rec["AbsImgHeight"]);
+ $newObj->setNavMode($a_rec["NavMode"]);
+ if ($a_rec["NavListMonWithPost"] == 0) {
+ $newObj->setNavModeListMonthsWithPostings(3);
+ } else {
+ $newObj->setNavModeListMonthsWithPostings($a_rec["NavListMonWithPost"]);
+ }
+ //$newObj->setNavModeListPostings($a_rec["NavListPost"]);
+ $newObj->setNavModeListMonths($a_rec["NavListMon"]);
+ $newObj->setKeywords($a_rec["Keywords"]);
+ $newObj->setAuthors($a_rec["Authors"]);
+ $newObj->setOrder(trim($a_rec["NavOrder"])
+ ? explode(";", $a_rec["NavOrder"])
+ : null);
+ $newObj->setOverviewPostings($a_rec["OvPost"]);
+
+ $newObj->update();
+
+ // handle image(s)
+ if ($a_rec["Img"]) {
+ $dir = str_replace("..", "", $a_rec["Dir"]);
+ if ($dir != "" && $this->getImportDirectory() != "") {
+ $source_dir = $this->getImportDirectory() . "/" . $dir;
+ $target_dir = ilObjBlog::initStorage($newObj->getId());
+ ilUtil::rCopy($source_dir, $target_dir);
+ }
+ }
- if($a_rec["Style"])
- {
- self::$style_map[$a_rec["Style"]][] = $newObj->getId();
- }
- $a_mapping->addMapping("Modules/Blog", "blog", $a_rec["Id"], $newObj->getId());
- break;
+ if ($a_rec["Style"]) {
+ self::$style_map[$a_rec["Style"]][] = $newObj->getId();
+ }
+ $a_mapping->addMapping("Modules/Blog", "blog", $a_rec["Id"], $newObj->getId());
+ break;
- case "blog_posting":
- $blog_id = (int) $a_mapping->getMapping("Modules/Blog", "blog", $a_rec["BlogId"]);
- if($blog_id)
- {
- include_once("./Modules/Blog/classes/class.ilBlogPosting.php");
- $newObj = new ilBlogPosting();
- $newObj->setBlogId($blog_id);
- $newObj->setTitle($a_rec["Title"]);
- $newObj->setCreated(new ilDateTime($a_rec["Created"], IL_CAL_DATETIME));
- $newObj->setApproved($a_rec["Approved"]);
-
- // parse export id into local id (if possible)
- $author = $this->parseObjectExportId($a_rec["Author"], -1);
- $newObj->setAuthor($author["id"]);
-
- $newObj->create(true);
-
- // keywords
- $keywords = array();
- for($loop = 0; $loop < 1000; $loop++)
- {
- if(isset($a_rec["Keyword".$loop]))
- {
- $keyword = trim($a_rec["Keyword".$loop]);
- if(strlen($keyword))
- {
- $keywords[] = $keyword;
- }
- }
- }
- if(sizeof($keywords))
- {
- $newObj->updateKeywords($keywords);
- }
-
- $a_mapping->addMapping("Services/COPage", "pg", "blp:".$a_rec["Id"], "blp:".$newObj->getId());
- }
- break;
- }
- }
+ case "blog_posting":
+ $blog_id = (int) $a_mapping->getMapping("Modules/Blog", "blog", $a_rec["BlogId"]);
+ if ($blog_id) {
+ include_once("./Modules/Blog/classes/class.ilBlogPosting.php");
+ $newObj = new ilBlogPosting();
+ $newObj->setBlogId($blog_id);
+ $newObj->setTitle($a_rec["Title"]);
+ $newObj->setCreated(new ilDateTime($a_rec["Created"], IL_CAL_DATETIME));
+ $newObj->setApproved($a_rec["Approved"]);
+
+ // parse export id into local id (if possible)
+ $author = $this->parseObjectExportId($a_rec["Author"], -1);
+ $newObj->setAuthor($author["id"]);
+
+ $newObj->create(true);
+
+ // keywords
+ $keywords = array();
+ for ($loop = 0; $loop < 1000; $loop++) {
+ if (isset($a_rec["Keyword" . $loop])) {
+ $keyword = trim($a_rec["Keyword" . $loop]);
+ if (strlen($keyword)) {
+ $keywords[] = $keyword;
+ }
+ }
+ }
+ if (sizeof($keywords)) {
+ $newObj->updateKeywords($keywords);
+ }
+
+ $a_mapping->addMapping("Services/COPage", "pg", "blp:" . $a_rec["Id"], "blp:" . $newObj->getId());
+ }
+ break;
+ }
+ }
}
-
-?>
\ No newline at end of file
diff --git a/Modules/Blog/classes/class.ilBlogExerciseGUI.php b/Modules/Blog/classes/class.ilBlogExerciseGUI.php
index 167ff22ec6556f0c9c9a169b60f86082fe8932b3..ca3a087e3b9c695971ce433a1f15257088213a40 100644
--- a/Modules/Blog/classes/class.ilBlogExerciseGUI.php
+++ b/Modules/Blog/classes/class.ilBlogExerciseGUI.php
@@ -2,8 +2,8 @@
/* Copyright (c) 1998-2009 ILIAS open source, Extended GPL, see docs/LICENSE */
-include_once "Modules/Exercise/classes/class.ilExAssignment.php";
-include_once "Modules/Exercise/classes/class.ilExSubmission.php";
+include_once "Modules/Exercise/classes/class.ilExAssignment.php";
+include_once "Modules/Exercise/classes/class.ilExSubmission.php";
/**
* Class ilBlogExerciseGUI
@@ -11,277 +11,258 @@ include_once "Modules/Exercise/classes/class.ilExSubmission.php";
* @author Jörg Lützenkirchen
", $info);
- }
- }
- }
+ $tree = $DIC->repositoryTree();
+ $ilUser = $DIC->user();
+
+ $exercises = ilExSubmission::findUserFiles($ilUser->getId(), $a_node_id);
+ // #0022794
+ if (!$exercises) {
+ $exercises = ilExSubmission::findUserFiles($ilUser->getId(), $a_node_id . ".sec");
+ }
+ if ($exercises) {
+ $info = array();
+ foreach ($exercises as $exercise) {
+ // #9988
+ $active_ref = false;
+ foreach (ilObject::_getAllReferences($exercise["obj_id"]) as $ref_id) {
+ if (!$tree->isSaved($ref_id)) {
+ $active_ref = true;
+ break;
+ }
+ }
+ if ($active_ref) {
+ $part = self::getExerciseInfo($exercise["ass_id"]);
+ if ($part) {
+ $info[] = $part;
+ }
+ }
+ }
+ if (sizeof($info)) {
+ return implode("
", $info);
+ }
+ }
+ }
- protected static function getExerciseInfo($a_assignment_id)
- {
- global $DIC;
+ protected static function getExerciseInfo($a_assignment_id)
+ {
+ global $DIC;
- $ui = $DIC->ui();
+ $ui = $DIC->ui();
- $links = [];
- $buttons = [];
- $elements = [];
+ $links = [];
+ $buttons = [];
+ $elements = [];
- $lng = $DIC->language();
- $ilCtrl = $DIC->ctrl();
- $ilUser = $DIC->user();
-
- $ass = new ilExAssignment($a_assignment_id);
- $exercise_id = $ass->getExerciseId();
- if(!$exercise_id)
- {
- return;
- }
-
- // is the assignment still open?
- $times_up = $ass->afterDeadlineStrict();
-
- // exercise goto
- include_once "./Services/Link/classes/class.ilLink.php";
- $exc_ref_id = array_shift(ilObject::_getAllReferences($exercise_id));
- $exc_link = ilLink::_getStaticLink($exc_ref_id, "exc");
+ $lng = $DIC->language();
+ $ilCtrl = $DIC->ctrl();
+ $ilUser = $DIC->user();
+
+ $ass = new ilExAssignment($a_assignment_id);
+ $exercise_id = $ass->getExerciseId();
+ if (!$exercise_id) {
+ return;
+ }
+
+ // is the assignment still open?
+ $times_up = $ass->afterDeadlineStrict();
+
+ // exercise goto
+ include_once "./Services/Link/classes/class.ilLink.php";
+ $exc_ref_id = array_shift(ilObject::_getAllReferences($exercise_id));
+ $exc_link = ilLink::_getStaticLink($exc_ref_id, "exc");
- $text = sprintf($lng->txt("blog_exercise_info"),
- $ass->getTitle(),
- ilObject::_lookupTitle($exercise_id));
- $links[] = $ui->factory()->link()->standard(ilObject::_lookupTitle($exercise_id), $exc_link);
-
- // submit button
- if(!$times_up)
- {
- $ilCtrl->setParameterByClass("ilblogexercisegui", "ass", $a_assignment_id);
- $submit_link = $ilCtrl->getLinkTargetByClass("ilblogexercisegui", "finalize");
- $ilCtrl->setParameterByClass("ilblogexercisegui", "ass", "");
+ $text = sprintf(
+ $lng->txt("blog_exercise_info"),
+ $ass->getTitle(),
+ ilObject::_lookupTitle($exercise_id)
+ );
+ $links[] = $ui->factory()->link()->standard(ilObject::_lookupTitle($exercise_id), $exc_link);
+
+ // submit button
+ if (!$times_up) {
+ $ilCtrl->setParameterByClass("ilblogexercisegui", "ass", $a_assignment_id);
+ $submit_link = $ilCtrl->getLinkTargetByClass("ilblogexercisegui", "finalize");
+ $ilCtrl->setParameterByClass("ilblogexercisegui", "ass", "");
- $buttons[] = $ui->factory()->button()->primary($lng->txt("blog_finalize_blog"), $submit_link);
- }
-
- // submitted files
- include_once "Modules/Exercise/classes/class.ilExSubmission.php";
- $submission = new ilExSubmission($ass, $ilUser->getId());
- if($submission->hasSubmitted())
- {
- // #16888
- $submitted = $submission->getSelectedObject();
-
- $ilCtrl->setParameterByClass("ilblogexercisegui", "ass", $a_assignment_id);
- $dl_link = $ilCtrl->getLinkTargetByClass("ilblogexercisegui", "downloadExcSubFile");
- $ilCtrl->setParameterByClass("ilblogexercisegui", "ass", "");
-
- $rel = ilDatePresentation::useRelativeDates();
- ilDatePresentation::setUseRelativeDates(false);
+ $buttons[] = $ui->factory()->button()->primary($lng->txt("blog_finalize_blog"), $submit_link);
+ }
+
+ // submitted files
+ include_once "Modules/Exercise/classes/class.ilExSubmission.php";
+ $submission = new ilExSubmission($ass, $ilUser->getId());
+ if ($submission->hasSubmitted()) {
+ // #16888
+ $submitted = $submission->getSelectedObject();
+
+ $ilCtrl->setParameterByClass("ilblogexercisegui", "ass", $a_assignment_id);
+ $dl_link = $ilCtrl->getLinkTargetByClass("ilblogexercisegui", "downloadExcSubFile");
+ $ilCtrl->setParameterByClass("ilblogexercisegui", "ass", "");
+
+ $rel = ilDatePresentation::useRelativeDates();
+ ilDatePresentation::setUseRelativeDates(false);
- $text .= "
".sprintf($lng->txt("blog_exercise_submitted_info"),
- ilDatePresentation::formatDate(new ilDateTime($submitted["ts"], IL_CAL_DATETIME)),
- "");
-
- ilDatePresentation::setUseRelativeDates($rel);
- $buttons[] = $ui->factory()->button()->standard($lng->txt("blog_download_submission"), $dl_link);
- }
-
-
- // work instructions incl. files
-
- $tooltip = "";
+ $text .= "
" . sprintf(
+ $lng->txt("blog_exercise_submitted_info"),
+ ilDatePresentation::formatDate(new ilDateTime($submitted["ts"], IL_CAL_DATETIME)),
+ ""
+ );
+
+ ilDatePresentation::setUseRelativeDates($rel);
+ $buttons[] = $ui->factory()->button()->standard($lng->txt("blog_download_submission"), $dl_link);
+ }
+
+
+ // work instructions incl. files
+
+ $tooltip = "";
- $inst = $ass->getInstruction();
- if($inst)
- {
- $tooltip .= nl2br($inst);
- }
+ $inst = $ass->getInstruction();
+ if ($inst) {
+ $tooltip .= nl2br($inst);
+ }
- $ass_files = $ass->getFiles();
- if (count($ass_files) > 0)
- {
- $tooltip .= "
";
-
- foreach($ass_files as $file)
- {
- $ilCtrl->setParameterByClass("ilblogexercisegui", "ass", $a_assignment_id);
- $ilCtrl->setParameterByClass("ilblogexercisegui", "file", urlencode($file["name"]));
- $dl_link = $ilCtrl->getLinkTargetByClass("ilblogexercisegui", "downloadExcAssFile");
- $ilCtrl->setParameterByClass("ilblogexercisegui", "file", "");
- $ilCtrl->setParameterByClass("ilblogexercisegui", "ass", "");
+ $ass_files = $ass->getFiles();
+ if (count($ass_files) > 0) {
+ $tooltip .= "
";
+
+ foreach ($ass_files as $file) {
+ $ilCtrl->setParameterByClass("ilblogexercisegui", "ass", $a_assignment_id);
+ $ilCtrl->setParameterByClass("ilblogexercisegui", "file", urlencode($file["name"]));
+ $dl_link = $ilCtrl->getLinkTargetByClass("ilblogexercisegui", "downloadExcAssFile");
+ $ilCtrl->setParameterByClass("ilblogexercisegui", "file", "");
+ $ilCtrl->setParameterByClass("ilblogexercisegui", "ass", "");
- $items[] = $ui->renderer()->render($ui->factory()->button()->shy($file["name"], $dl_link));
- }
- $list = $ui->factory()->listing()->unordered($items);
- $tooltip .= $ui->renderer()->render($list);
- }
-
- if($tooltip)
- {
- $modal = $ui->factory()->modal()->roundtrip($lng->txt("exc_instruction"), $ui->factory()->legacy($tooltip))
- ->withCancelButtonLabel("close");
- $elements[] = $modal;
- $buttons[] = $ui->factory()->button()->standard($lng->txt("exc_instruction"), '#')
- ->withOnClick($modal->getShowSignal());
+ $items[] = $ui->renderer()->render($ui->factory()->button()->shy($file["name"], $dl_link));
+ }
+ $list = $ui->factory()->listing()->unordered($items);
+ $tooltip .= $ui->renderer()->render($list);
+ }
+
+ if ($tooltip) {
+ $modal = $ui->factory()->modal()->roundtrip($lng->txt("exc_instruction"), $ui->factory()->legacy($tooltip))
+ ->withCancelButtonLabel("close");
+ $elements[] = $modal;
+ $buttons[] = $ui->factory()->button()->standard($lng->txt("exc_instruction"), '#')
+ ->withOnClick($modal->getShowSignal());
+ }
- }
+ $elements[] = $ui->factory()->messageBox()->info($text)
+ ->withLinks($links)
+ ->withButtons($buttons);
- $elements[] = $ui->factory()->messageBox()->info($text)
- ->withLinks($links)
- ->withButtons($buttons);
+ return $ui->renderer()->render($elements);
+ }
+
+ protected function downloadExcAssFile()
+ {
+ if ($this->file) {
+ include_once "Modules/Exercise/classes/class.ilExAssignment.php";
+ $ass = new ilExAssignment($this->ass_id);
+ $ass_files = $ass->getFiles();
+ if (count($ass_files) > 0) {
+ foreach ($ass_files as $file) {
+ if ($file["name"] == $this->file) {
+ ilUtil::deliverFile($file["fullpath"], $file["name"]);
+ }
+ }
+ }
+ }
+ }
+
+ protected function downloadExcSubFile()
+ {
+ $ilUser = $this->user;
+
+ $ass = new ilExAssignment($this->ass_id);
+ $submission = new ilExSubmission($ass, $ilUser->getId());
+ $submitted = $submission->getFiles();
+ if (count($submitted) > 0) {
+ $submitted = array_pop($submitted);
- return $ui->renderer()->render($elements);
- }
-
- protected function downloadExcAssFile()
- {
- if($this->file)
- {
- include_once "Modules/Exercise/classes/class.ilExAssignment.php";
- $ass = new ilExAssignment($this->ass_id);
- $ass_files = $ass->getFiles();
- if (count($ass_files) > 0)
- {
- foreach($ass_files as $file)
- {
- if($file["name"] == $this->file)
- {
- ilUtil::deliverFile($file["fullpath"], $file["name"]);
- }
- }
- }
- }
- }
-
- protected function downloadExcSubFile()
- {
- $ilUser = $this->user;
-
- $ass = new ilExAssignment($this->ass_id);
- $submission = new ilExSubmission($ass, $ilUser->getId());
- $submitted = $submission->getFiles();
- if (count($submitted) > 0)
- {
- $submitted = array_pop($submitted);
+ $user_data = ilObjUser::_lookupName($submitted["user_id"]);
+ $title = ilObject::_lookupTitle($submitted["obj_id"]) . " - " .
+ $ass->getTitle() . " - " .
+ $user_data["firstname"] . " " .
+ $user_data["lastname"] . " (" .
+ $user_data["login"] . ").zip";
- $user_data = ilObjUser::_lookupName($submitted["user_id"]);
- $title = ilObject::_lookupTitle($submitted["obj_id"])." - ".
- $ass->getTitle()." - ".
- $user_data["firstname"]." ".
- $user_data["lastname"]." (".
- $user_data["login"].").zip";
+ ilUtil::deliverFile($submitted["filename"], $title);
+ }
+ }
+
+ /**
+ * Finalize and submit blog to exercise
+ */
+ protected function finalize()
+ {
+ $ilCtrl = $this->ctrl;
+ $lng = $this->lng;
+
+ include_once "Modules/Exercise/classes/class.ilExSubmissionBaseGUI.php";
+ include_once "Modules/Exercise/classes/class.ilExSubmissionObjectGUI.php";
+ $exc_gui = ilExSubmissionObjectGUI::initGUIForSubmit($this->ass_id);
+ $exc_gui->submitBlog($this->node_id);
- ilUtil::deliverFile($submitted["filename"], $title);
- }
- }
-
- /**
- * Finalize and submit blog to exercise
- */
- protected function finalize()
- {
- $ilCtrl = $this->ctrl;
- $lng = $this->lng;
-
- include_once "Modules/Exercise/classes/class.ilExSubmissionBaseGUI.php";
- include_once "Modules/Exercise/classes/class.ilExSubmissionObjectGUI.php";
- $exc_gui = ilExSubmissionObjectGUI::initGUIForSubmit($this->ass_id);
- $exc_gui->submitBlog($this->node_id);
-
- ilUtil::sendSuccess($lng->txt("blog_finalized"), true);
- $ilCtrl->returnToParent($this);
- }
+ ilUtil::sendSuccess($lng->txt("blog_finalized"), true);
+ $ilCtrl->returnToParent($this);
+ }
}
diff --git a/Modules/Blog/classes/class.ilBlogExporter.php b/Modules/Blog/classes/class.ilBlogExporter.php
index 234788c2104fc3457bdd1466c915bae705fe0ccf..4d8ae86dea42c4ca86be0598125ccc391af5f0c4 100644
--- a/Modules/Blog/classes/class.ilBlogExporter.php
+++ b/Modules/Blog/classes/class.ilBlogExporter.php
@@ -1,104 +1,96 @@
-
- * @version $Id$
- *
- * @ingroup ModulesBlog
- */
-class ilBlogExporter extends ilXmlExporter
-{
- protected $ds;
-
- public function init()
- {
- include_once("./Modules/Blog/classes/class.ilBlogDataSet.php");
- $this->ds = new ilBlogDataSet();
- $this->ds->setDSPrefix("ds");
- }
-
- public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids)
- {
- $res = array();
-
- // postings
- include_once("./Modules/Blog/classes/class.ilBlogPosting.php");
- $pg_ids = array();
- foreach ($a_ids as $id)
- {
- $pages = ilBlogPosting::getAllPostings($id);
- foreach (array_keys($pages) as $p)
- {
- $pg_ids[] = "blp:".$p;
- }
- }
- if(sizeof($pg_ids))
- {
- $res[] = array(
- "component" => "Services/COPage",
- "entity" => "pg",
- "ids" => $pg_ids
- );
- }
-
- // style
- $style_ids = array();
- foreach ($a_ids as $id)
- {
- include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php");
- $style_id = ilObjStyleSheet::lookupObjectStyle($id);
- if ($style_id > 0)
- {
- $style_ids[] = $style_id;
- }
- }
- if(sizeof($style_ids))
- {
- $res[] = array(
- "component" => "Services/Style",
- "entity" => "sty",
- "ids" => $style_ids
- );
- }
-
- // service settings
- $res[] = array(
- "component" => "Services/Object",
- "entity" => "common",
- "ids" => $a_ids);
-
- return $res;
- }
-
- public function getXmlRepresentation($a_entity, $a_schema_version, $a_id)
- {
- $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute);
- return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true);
- }
-
- public function getValidSchemaVersions($a_entity)
- {
- return array (
- "4.3.0" => array(
- "namespace" => "http://www.ilias.de/Modules/Blog/4_3",
- "xsd_file" => "ilias_blog_4_3.xsd",
- "uses_dataset" => true,
- "min" => "4.3.0",
- "max" => "4.9.9"),
- "5.0.0" => array(
- "namespace" => "http://www.ilias.de/Modules/Blog/5_0",
- "xsd_file" => "ilias_blog_5_0.xsd",
- "uses_dataset" => true,
- "min" => "5.0.0",
- "max" => "")
-
- );
- }
-
-}
-?>
\ No newline at end of file
+
+ * @version $Id$
+ *
+ * @ingroup ModulesBlog
+ */
+class ilBlogExporter extends ilXmlExporter
+{
+ protected $ds;
+
+ public function init()
+ {
+ include_once("./Modules/Blog/classes/class.ilBlogDataSet.php");
+ $this->ds = new ilBlogDataSet();
+ $this->ds->setDSPrefix("ds");
+ }
+
+ public function getXmlExportTailDependencies($a_entity, $a_target_release, $a_ids)
+ {
+ $res = array();
+
+ // postings
+ include_once("./Modules/Blog/classes/class.ilBlogPosting.php");
+ $pg_ids = array();
+ foreach ($a_ids as $id) {
+ $pages = ilBlogPosting::getAllPostings($id);
+ foreach (array_keys($pages) as $p) {
+ $pg_ids[] = "blp:" . $p;
+ }
+ }
+ if (sizeof($pg_ids)) {
+ $res[] = array(
+ "component" => "Services/COPage",
+ "entity" => "pg",
+ "ids" => $pg_ids
+ );
+ }
+
+ // style
+ $style_ids = array();
+ foreach ($a_ids as $id) {
+ include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php");
+ $style_id = ilObjStyleSheet::lookupObjectStyle($id);
+ if ($style_id > 0) {
+ $style_ids[] = $style_id;
+ }
+ }
+ if (sizeof($style_ids)) {
+ $res[] = array(
+ "component" => "Services/Style",
+ "entity" => "sty",
+ "ids" => $style_ids
+ );
+ }
+
+ // service settings
+ $res[] = array(
+ "component" => "Services/Object",
+ "entity" => "common",
+ "ids" => $a_ids);
+
+ return $res;
+ }
+
+ public function getXmlRepresentation($a_entity, $a_schema_version, $a_id)
+ {
+ $this->ds->setExportDirectories($this->dir_relative, $this->dir_absolute);
+ return $this->ds->getXmlRepresentation($a_entity, $a_schema_version, $a_id, "", true, true);
+ }
+
+ public function getValidSchemaVersions($a_entity)
+ {
+ return array(
+ "4.3.0" => array(
+ "namespace" => "http://www.ilias.de/Modules/Blog/4_3",
+ "xsd_file" => "ilias_blog_4_3.xsd",
+ "uses_dataset" => true,
+ "min" => "4.3.0",
+ "max" => "4.9.9"),
+ "5.0.0" => array(
+ "namespace" => "http://www.ilias.de/Modules/Blog/5_0",
+ "xsd_file" => "ilias_blog_5_0.xsd",
+ "uses_dataset" => true,
+ "min" => "5.0.0",
+ "max" => "")
+
+ );
+ }
+}
diff --git a/Modules/Blog/classes/class.ilBlogImporter.php b/Modules/Blog/classes/class.ilBlogImporter.php
index cdce084fd0ba6cc2b436f69f6a7cdc635a5c3019..a5982d4c602736dd120c8593f4fbac324def7edd 100644
--- a/Modules/Blog/classes/class.ilBlogImporter.php
+++ b/Modules/Blog/classes/class.ilBlogImporter.php
@@ -12,61 +12,60 @@ include_once("./Services/Export/classes/class.ilXmlImporter.php");
*/
class ilBlogImporter extends ilXmlImporter
{
- protected $ds;
-
- /**
- * Initialisation
- */
- function init()
- {
- include_once("./Modules/Blog/classes/class.ilBlogDataSet.php");
- $this->ds = new ilBlogDataSet();
- $this->ds->setDSPrefix("ds");
- }
+ protected $ds;
+
+ /**
+ * Initialisation
+ */
+ public function init()
+ {
+ include_once("./Modules/Blog/classes/class.ilBlogDataSet.php");
+ $this->ds = new ilBlogDataSet();
+ $this->ds->setDSPrefix("ds");
+ }
- /**
- * Import XML
- *
- * @param
- * @return
- */
- function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping)
- {
- $this->ds->setImportDirectory($this->getImportDirectory());
- include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php");
- $parser = new ilDataSetImportParser($a_entity, $this->getSchemaVersion(),
- $a_xml, $this->ds, $a_mapping);
- }
-
- /**
- * Final processing
- *
- * @param array mapping array
- */
- function finalProcessing($a_mapping)
- {
- include_once("./Modules/Blog/classes/class.ilBlogPosting.php");
- $blp_map = $a_mapping->getMappingsOfEntity("Services/COPage", "pg");
- foreach ($blp_map as $blp_id)
- {
- $blp_id = substr($blp_id, 4);
- $blog_id = ilBlogPosting::lookupBlogId($blp_id);
- ilBlogPosting::_writeParentId("blp", $blp_id, $blog_id);
- }
-
- include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php");
- $sty_map = $a_mapping->getMappingsOfEntity("Services/Style", "sty");
- foreach ($sty_map as $old_sty_id => $new_sty_id)
- {
- if(is_array(ilBlogDataSet::$style_map[$old_sty_id]))
- {
- foreach(ilBlogDataSet::$style_map[$old_sty_id] as $blog_id)
- {
- ilObjStyleSheet::writeStyleUsage($blog_id, $new_sty_id);
- }
- }
- }
- }
+ /**
+ * Import XML
+ *
+ * @param
+ * @return
+ */
+ public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping)
+ {
+ $this->ds->setImportDirectory($this->getImportDirectory());
+ include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php");
+ $parser = new ilDataSetImportParser(
+ $a_entity,
+ $this->getSchemaVersion(),
+ $a_xml,
+ $this->ds,
+ $a_mapping
+ );
+ }
+
+ /**
+ * Final processing
+ *
+ * @param array mapping array
+ */
+ public function finalProcessing($a_mapping)
+ {
+ include_once("./Modules/Blog/classes/class.ilBlogPosting.php");
+ $blp_map = $a_mapping->getMappingsOfEntity("Services/COPage", "pg");
+ foreach ($blp_map as $blp_id) {
+ $blp_id = substr($blp_id, 4);
+ $blog_id = ilBlogPosting::lookupBlogId($blp_id);
+ ilBlogPosting::_writeParentId("blp", $blp_id, $blog_id);
+ }
+
+ include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php");
+ $sty_map = $a_mapping->getMappingsOfEntity("Services/Style", "sty");
+ foreach ($sty_map as $old_sty_id => $new_sty_id) {
+ if (is_array(ilBlogDataSet::$style_map[$old_sty_id])) {
+ foreach (ilBlogDataSet::$style_map[$old_sty_id] as $blog_id) {
+ ilObjStyleSheet::writeStyleUsage($blog_id, $new_sty_id);
+ }
+ }
+ }
+ }
}
-
-?>
\ No newline at end of file
diff --git a/Modules/Blog/classes/class.ilBlogNewsRendererGUI.php b/Modules/Blog/classes/class.ilBlogNewsRendererGUI.php
index c20fa81f5a0b26ada47066481efc033657f0e4a0..3b380fdccf40dc2b8ef8ee17773ee94a3f5c936c 100644
--- a/Modules/Blog/classes/class.ilBlogNewsRendererGUI.php
+++ b/Modules/Blog/classes/class.ilBlogNewsRendererGUI.php
@@ -12,25 +12,21 @@ include_once("./Services/News/classes/class.ilNewsDefaultRendererGUI.php");
*/
class ilBlogNewsRendererGUI extends ilNewsDefaultRendererGUI
{
- /**
- * Get object link
- *
- * @return string link href url
- */
- function getObjectLink()
- {
- include_once("./Services/Link/classes/class.ilLink.php");
- $n = $this->getNewsItem();
- $add = "";
- if ($n->getContextSubObjType() == "blp"
- && $n->getContextSubObjId() > 0)
- {
- $add = "_".$n->getContextSubObjId();
- }
-
- return ilLink::_getLink($this->getNewsRefId(), "", array(), $add);
- }
+ /**
+ * Get object link
+ *
+ * @return string link href url
+ */
+ public function getObjectLink()
+ {
+ include_once("./Services/Link/classes/class.ilLink.php");
+ $n = $this->getNewsItem();
+ $add = "";
+ if ($n->getContextSubObjType() == "blp"
+ && $n->getContextSubObjId() > 0) {
+ $add = "_" . $n->getContextSubObjId();
+ }
+ return ilLink::_getLink($this->getNewsRefId(), "", array(), $add);
+ }
}
-
-?>
\ No newline at end of file
diff --git a/Modules/Blog/classes/class.ilBlogPosting.php b/Modules/Blog/classes/class.ilBlogPosting.php
index 54989857f85483ba511791fa835c86ff0d0f9a77..efe749b09d5cd3479d5d00934cf58240e9fde280 100644
--- a/Modules/Blog/classes/class.ilBlogPosting.php
+++ b/Modules/Blog/classes/class.ilBlogPosting.php
@@ -12,637 +12,610 @@ include_once("./Services/COPage/classes/class.ilPageObject.php");
* @ingroup ModulesBlog
*/
class ilBlogPosting extends ilPageObject
-{
- protected $title; // [string]
- protected $created; // [ilDateTime]
- protected $blog_node_id; // [int]
- protected $blog_node_is_wsp; // [bool]
- protected $author; // [int]
- protected $approved; // [bool]
-
- /**
- * Get parent type
- *
- * @return string parent type
- */
- function getParentType()
- {
- return "blp";
- }
-
-
- /**
- * Set title
- *
- * @param string $a_title
- */
- function setTitle($a_title)
- {
- $this->title = $a_title;
- }
-
- /**
- * Get title
- *
- * @return string
- */
- function getTitle()
- {
- return $this->title;
- }
-
- /**
- * Set blog object id
- *
- * @param int $a_id
- */
- function setBlogId($a_id)
- {
- $this->setParentId($a_id);
- }
-
- /**
- * Get blog object id
- *
- * @return int
- */
- function getBlogId()
- {
- return $this->getParentId();
- }
-
- /**
- * Set creation date
- *
- * @param ilDateTime $a_date
- */
- function setCreated(ilDateTime $a_date)
- {
- $this->created = $a_date;
- }
-
- /**
- * Get creation date
- *
- * @return ilDateTime
- */
- function getCreated()
- {
- return $this->created;
- }
-
- /**
- * Set author user id
- *
- * @param int $a_id
- */
- function setAuthor($a_id)
- {
- $this->author = (int)$a_id;
- }
-
- /**
- * Get author user id
- *
- * @return int
- */
- function getAuthor()
- {
- return $this->author;
- }
-
- /**
- * Toggle approval status
- */
- function setApproved($a_status)
- {
- $this->approved = (bool)$a_status;
- }
-
- /**
- * Get approved status
- *
- * @return bool
- */
- function isApproved()
- {
- return (bool)$this->approved;
- }
-
- /**
- * Create new blog posting
- */
- function create($a_import = false)
- {
- $ilDB = $this->db;
-
- $id = $ilDB->nextId("il_blog_posting");
- $this->setId($id);
-
- if(!$a_import)
- {
- $created = ilUtil::now();
- }
- else
- {
- $created = $this->getCreated()->get(IL_CAL_DATETIME);
- }
-
- // we are using a separate creation date to enable sorting without JOINs
-
- $query = "INSERT INTO il_blog_posting (id, title, blog_id, created, author, approved)".
- " VALUES (".
- $ilDB->quote($this->getId(), "integer").",".
- $ilDB->quote($this->getTitle(), "text").",".
- $ilDB->quote($this->getBlogId(), "integer").",".
- $ilDB->quote($created, "timestamp").",".
- $ilDB->quote($this->getAuthor(), "integer").",".
- $ilDB->quote($this->isApproved(), "integer").")"; // #16526 - import
- $ilDB->manipulate($query);
-
- if(!$a_import)
- {
- parent::create();
- // $this->saveInternalLinks($this->getXMLContent());
- }
- }
-
- /**
- * Update blog posting
- *
- * @param bool $a_validate
- * @param bool $a_no_history
- * @param bool $a_notify
- * @param string $a_notify_action
- * @return boolean
- */
- function update($a_validate = true, $a_no_history = false, $a_notify = true, $a_notify_action = "update")
- {
- $ilDB = $this->db;
-
- // blog_id, author and created cannot be changed
-
- $query = "UPDATE il_blog_posting SET".
- " title = ".$ilDB->quote($this->getTitle(), "text").
- ",created = ".$ilDB->quote($this->getCreated()->get(IL_CAL_DATETIME), "text").
- ",approved =".$ilDB->quote($this->isApproved(), "integer").
- " WHERE id = ".$ilDB->quote($this->getId(), "integer");
- $ilDB->manipulate($query);
-
- parent::update($a_validate, $a_no_history);
-
- if($a_notify && $this->getActive())
- {
- include_once "Modules/Blog/classes/class.ilObjBlog.php";
- ilObjBlog::sendNotification($a_notify_action, $this->blog_node_is_wsp, $this->blog_node_id, $this->getId());
- }
-
- return true;
- }
-
- /**
- * Read blog posting
- */
- function read()
- {
- $ilDB = $this->db;
-
- $query = "SELECT * FROM il_blog_posting".
- " WHERE id = ".$ilDB->quote($this->getId(), "integer");
- $set = $ilDB->query($query);
- $rec = $ilDB->fetchAssoc($set);
-
- $this->setTitle($rec["title"]);
- $this->setBlogId($rec["blog_id"]);
- $this->setCreated(new ilDateTime($rec["created"], IL_CAL_DATETIME));
- $this->setAuthor($rec["author"]);
- if((bool)$rec["approved"])
- {
- $this->setApproved(true);
- }
-
- // when posting is deactivated it should loose the approval
- $this->addUpdateListener($this, "checkApproval");
-
- parent::read();
- }
-
- function checkApproval()
- {
- if(!$this->getActive() && $this->isApproved())
- {
- $this->approved = false;
- $this->update();
- }
- }
-
- /**
- * Delete blog posting and all related data
- *
- * @return bool
- */
- function delete()
- {
- $ilDB = $this->db;
-
- include_once("./Services/News/classes/class.ilNewsItem.php");
- ilNewsItem::deleteNewsOfContext($this->getBlogId(),
- "blog", $this->getId(), $this->getParentType());
-
- $query = "DELETE FROM il_blog_posting".
- " WHERE id = ".$ilDB->quote($this->getId(), "integer");
- $ilDB->manipulate($query);
-
- parent::delete();
-
- return true;
- }
-
- /**
- * Unpublish
- */
- public function unpublish()
- {
- $this->setApproved(false);
- $this->setActive(false);
- $this->update(true, false, false);
-
- include_once("./Services/News/classes/class.ilNewsItem.php");
- ilNewsItem::deleteNewsOfContext($this->getBlogId(),
- "blog", $this->getId(), $this->getParentType());
- }
-
-
- /**
- * Delete all postings for blog
- *
- * @param int $a_blog_id
- */
- static function deleteAllBlogPostings($a_blog_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- include_once 'Services/MetaData/classes/class.ilMD.php';
-
- $query = "SELECT * FROM il_blog_posting".
- " WHERE blog_id = ".$ilDB->quote($a_blog_id, "integer");
- $set = $ilDB->query($query);
- while($rec = $ilDB->fetchAssoc($set))
- {
- // delete all md keywords
- $md_obj = new ilMD($a_blog_id, $rec["id"], "blp");
- if(is_object($md_section = $md_obj->getGeneral()))
- {
- foreach($md_section->getKeywordIds() as $id)
- {
- $md_key = $md_section->getKeyword($id);
- $md_key->delete();
- }
- }
-
- $post = new ilBlogPosting($rec["id"]);
- $post->delete();
- }
- }
-
- /**
- * Lookup blog id
- *
- * @param int $a_posting_id
- * @return int
- */
- static function lookupBlogId($a_posting_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $query = "SELECT blog_id FROM il_blog_posting".
- " WHERE id = ".$ilDB->quote($a_posting_id, "integer");
- $set = $ilDB->query($query);
- if ($rec = $ilDB->fetchAssoc($set))
- {
- return $rec["blog_id"];
- }
- return false;
- }
-
- /**
- * Get all postings of blog
- *
- * @param int $a_blog_id
- * @param int $a_limit
- * @param int $a_offset
- * @return array
- */
- static function getAllPostings($a_blog_id, $a_limit = 1000, $a_offset = 0)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $pages = parent::getAllPages("blp", $a_blog_id);
-
- if($a_limit)
- {
- $ilDB->setLimit($a_limit, $a_offset);
- }
-
- $query = "SELECT * FROM il_blog_posting".
- " WHERE blog_id = ".$ilDB->quote($a_blog_id, "integer").
- " ORDER BY created DESC";
- $set = $ilDB->query($query);
- $post = array();
- while($rec = $ilDB->fetchAssoc($set))
- {
- if (isset($pages[$rec["id"]]))
- {
- $post[$rec["id"]] = $pages[$rec["id"]];
- $post[$rec["id"]]["title"] = $rec["title"];
- $post[$rec["id"]]["created"] = new ilDateTime($rec["created"], IL_CAL_DATETIME);
- $post[$rec["id"]]["author"] = $rec["author"];
- $post[$rec["id"]]["approved"] = (bool)$rec["approved"];
-
- foreach(self::getPageContributors("blp", $rec["id"]) as $editor)
- {
- if($editor["user_id"] != $rec["author"])
- {
- $post[$rec["id"]]["editors"][] = $editor["user_id"];
- }
- }
- }
- }
-
- return $post;
- }
-
- /**
- * Checks whether a posting exists
- *
- * @param int $a_blog_id
- * @param int $a_posting_id
- * @return bool
- */
- static function exists($a_blog_id, $a_posting_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $query = "SELECT id FROM il_blog_posting".
- " WHERE blog_id = ".$ilDB->quote($a_blog_id, "integer").
- " AND id = ".$ilDB->quote($a_posting_id, "integer");
- $set = $ilDB->query($query);
- if($rec = $ilDB->fetchAssoc($set))
- {
- return true;
- }
- return false;
- }
-
- /**
- * Get newest posting for blog
- *
- * @param int $a_blog_id
- * @return int
- */
- static function getLastPost($a_blog_id)
- {
- $data = self::getAllPostings($a_blog_id, 1);
- if($data)
- {
- return array_pop(array_keys($data));
- }
- }
-
- /**
- * Set blog node id (needed for notification)
- *
- * @param int $a_id
- * @param bool $a_is_in_workspace
- */
- public function setBlogNodeId($a_id, $a_is_in_workspace = false)
- {
- $this->blog_node_id = (int)$a_id;
- $this->blog_node_is_wsp = (bool)$a_is_in_workspace;
- }
-
- /**
- * Get all blogs where user has postings
- *
- * @param int $a_user_id
- * @return array
- */
- public static function searchBlogsByAuthor($a_user_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $ids = array();
-
- $sql = "SELECT DISTINCT(blog_id)".
- " FROM il_blog_posting".
- " WHERE author = ".$ilDB->quote($a_user_id);
- $set = $ilDB->query($sql);
- while($row = $ilDB->fetchAssoc($set))
- {
- $ids[] = $row["blog_id"];
- }
- return $ids;
- }
-
- public function getNotificationAbstract()
- {
- include_once "Modules/Blog/classes/class.ilBlogPostingGUI.php";
- $snippet = ilBlogPostingGUI::getSnippet($this->getId(), true);
-
- // making things more readable
- $snippet = str_replace('
', "\n", $snippet);
- $snippet = str_replace('
', "\n", $snippet);
- $snippet = str_replace('
");
- $snippet = str_replace("&", "&", $snippet);
- $snippet = "";
+ // only published items
+ $is_active = ilBlogPosting::_lookupActive($id, "blp");
+ if (!$is_active) {
+ continue;
+ }
+
+ // #16434
+ $snippet = strip_tags(ilBlogPostingGUI::getSnippet($id), "
");
+ $snippet = str_replace("&", "&", $snippet);
+ $snippet = "";
- $url = ilLink::_getStaticLink($a_wsp_id, "blog", true, "_".$id.$is_wsp);
- $url = str_replace("&", "&", $url);
+ $url = ilLink::_getStaticLink($a_wsp_id, "blog", true, "_" . $id . $is_wsp);
+ $url = str_replace("&", "&", $url);
- $feed_item = new ilFeedItem();
- $feed_item->setTitle(str_replace("&", "&", $item["title"])); // #16022
- $feed_item->setDate($item["created"]->get(IL_CAL_DATETIME));
- $feed_item->setDescription($snippet);
- $feed_item->setLink($url);
- $feed_item->setAbout($url);
- $feed->addItem($feed_item);
- }
-
- $feed->showFeed();
- exit();
- }
-
- function initDefaultRoles()
- {
- include_once './Services/AccessControl/classes/class.ilObjRole.php';
- $role = ilObjRole::createDefaultRole(
- 'il_blog_contributor_'.$this->getRefId(),
- "Contributor of blog obj_no.".$this->getId(),
- 'il_blog_contributor',
- $this->getRefId()
- );
-
- include_once './Services/AccessControl/classes/class.ilObjRole.php';
- $role = ilObjRole::createDefaultRole(
- 'il_blog_editor_'.$this->getRefId(),
- "Editor of blog obj_no.".$this->getId(),
- 'il_blog_editor',
- $this->getRefId()
- );
-
- return array();
- }
-
- function getLocalContributorRole($a_node_id)
- {
- $rbacreview = $this->rbacreview;
-
- foreach($rbacreview->getLocalRoles($a_node_id) as $role_id)
- {
- if(substr(ilObject::_lookupTitle($role_id), 0, 19) == "il_blog_contributor")
- {
- return $role_id;
- }
- }
- }
-
- function getLocalEditorRole($a_node_id)
- {
- $rbacreview = $this->rbacreview;
-
- foreach($rbacreview->getLocalRoles($a_node_id) as $role_id)
- {
- if(substr(ilObject::_lookupTitle($role_id), 0, 14) == "il_blog_editor")
- {
- return $role_id;
- }
- }
- }
-
- function getAllLocalRoles($a_node_id)
- {
- $rbacreview = $this->rbacreview;
-
- include_once "Services/AccessControl/classes/class.ilObjRole.php";
-
- $res = array();
- foreach($rbacreview->getLocalRoles($a_node_id) as $role_id)
- {
- $res[$role_id] = ilObjRole::_getTranslation(ilObject::_lookupTitle($role_id));
- }
-
- asort($res);
- return $res;
- }
-
- function getRolesWithContributeOrRedact($a_node_id)
- {
- $rbacreview = $this->rbacreview;
-
- include_once "Services/AccessControl/classes/class.ilObjRole.php";
-
- $contr_op_id = ilRbacReview::_getOperationIdByName("contribute");
- $redact_op_id = ilRbacReview::_getOperationIdByName("redact");
- $contr_role_id = $this->getLocalContributorRole($a_node_id);
- $editor_role_id = $this->getLocalEditorRole($a_node_id);
-
- $res = array();
- foreach($rbacreview->getParentRoleIds($a_node_id) as $role_id => $role)
- {
- if($role_id != $contr_role_id &&
- $role_id != $editor_role_id)
- {
- $all_ops = $rbacreview->getActiveOperationsOfRole($a_node_id, $role_id);
- if(in_array($contr_op_id, $all_ops) ||
- in_array($redact_op_id, $all_ops))
- {
- $res[$role_id] = ilObjRole:: _getTranslation($role["title"]);
- }
- }
- }
-
- return $res;
- }
-
- protected function handleQuotaUpdate()
- {
- include_once "Services/DiskQuota/classes/class.ilDiskQuotaHandler.php";
- ilDiskQuotaHandler::handleUpdatedSourceObject($this->getType(),
- $this->getId(),
- ilUtil::dirsize($this->initStorage($this->getId())),
- array($this->getId()));
- }
+ $feed_item = new ilFeedItem();
+ $feed_item->setTitle(str_replace("&", "&", $item["title"])); // #16022
+ $feed_item->setDate($item["created"]->get(IL_CAL_DATETIME));
+ $feed_item->setDescription($snippet);
+ $feed_item->setLink($url);
+ $feed_item->setAbout($url);
+ $feed->addItem($feed_item);
+ }
+
+ $feed->showFeed();
+ exit();
+ }
+
+ public function initDefaultRoles()
+ {
+ include_once './Services/AccessControl/classes/class.ilObjRole.php';
+ $role = ilObjRole::createDefaultRole(
+ 'il_blog_contributor_' . $this->getRefId(),
+ "Contributor of blog obj_no." . $this->getId(),
+ 'il_blog_contributor',
+ $this->getRefId()
+ );
+
+ include_once './Services/AccessControl/classes/class.ilObjRole.php';
+ $role = ilObjRole::createDefaultRole(
+ 'il_blog_editor_' . $this->getRefId(),
+ "Editor of blog obj_no." . $this->getId(),
+ 'il_blog_editor',
+ $this->getRefId()
+ );
+
+ return array();
+ }
+
+ public function getLocalContributorRole($a_node_id)
+ {
+ $rbacreview = $this->rbacreview;
+
+ foreach ($rbacreview->getLocalRoles($a_node_id) as $role_id) {
+ if (substr(ilObject::_lookupTitle($role_id), 0, 19) == "il_blog_contributor") {
+ return $role_id;
+ }
+ }
+ }
+
+ public function getLocalEditorRole($a_node_id)
+ {
+ $rbacreview = $this->rbacreview;
+
+ foreach ($rbacreview->getLocalRoles($a_node_id) as $role_id) {
+ if (substr(ilObject::_lookupTitle($role_id), 0, 14) == "il_blog_editor") {
+ return $role_id;
+ }
+ }
+ }
+
+ public function getAllLocalRoles($a_node_id)
+ {
+ $rbacreview = $this->rbacreview;
+
+ include_once "Services/AccessControl/classes/class.ilObjRole.php";
+
+ $res = array();
+ foreach ($rbacreview->getLocalRoles($a_node_id) as $role_id) {
+ $res[$role_id] = ilObjRole::_getTranslation(ilObject::_lookupTitle($role_id));
+ }
+
+ asort($res);
+ return $res;
+ }
+
+ public function getRolesWithContributeOrRedact($a_node_id)
+ {
+ $rbacreview = $this->rbacreview;
+
+ include_once "Services/AccessControl/classes/class.ilObjRole.php";
+
+ $contr_op_id = ilRbacReview::_getOperationIdByName("contribute");
+ $redact_op_id = ilRbacReview::_getOperationIdByName("redact");
+ $contr_role_id = $this->getLocalContributorRole($a_node_id);
+ $editor_role_id = $this->getLocalEditorRole($a_node_id);
+
+ $res = array();
+ foreach ($rbacreview->getParentRoleIds($a_node_id) as $role_id => $role) {
+ if ($role_id != $contr_role_id &&
+ $role_id != $editor_role_id) {
+ $all_ops = $rbacreview->getActiveOperationsOfRole($a_node_id, $role_id);
+ if (in_array($contr_op_id, $all_ops) ||
+ in_array($redact_op_id, $all_ops)) {
+ $res[$role_id] = ilObjRole:: _getTranslation($role["title"]);
+ }
+ }
+ }
+
+ return $res;
+ }
+
+ protected function handleQuotaUpdate()
+ {
+ include_once "Services/DiskQuota/classes/class.ilDiskQuotaHandler.php";
+ ilDiskQuotaHandler::handleUpdatedSourceObject(
+ $this->getType(),
+ $this->getId(),
+ ilUtil::dirsize($this->initStorage($this->getId())),
+ array($this->getId())
+ );
+ }
}
-
-?>
\ No newline at end of file
diff --git a/Modules/Blog/classes/class.ilObjBlogAccess.php b/Modules/Blog/classes/class.ilObjBlogAccess.php
index 7c64fe18364efb048ee2b743a742f84ac930feda..a5726e30dd543235303f700f4246d4ee0e268956 100644
--- a/Modules/Blog/classes/class.ilObjBlogAccess.php
+++ b/Modules/Blog/classes/class.ilObjBlogAccess.php
@@ -14,125 +14,115 @@ require_once('./Services/WebAccessChecker/interfaces/interface.ilWACCheckingClas
*/
class ilObjBlogAccess extends ilObjectAccess implements ilWACCheckingClass
{
- /**
- * @var ilObjUser
- */
- protected $user;
+ /**
+ * @var ilObjUser
+ */
+ protected $user;
- /**
- * @var ilAccessHandler
- */
- protected $access;
+ /**
+ * @var ilAccessHandler
+ */
+ protected $access;
- /**
- * Constructor
- */
- function __construct()
- {
- global $DIC;
+ /**
+ * Constructor
+ */
+ public function __construct()
+ {
+ global $DIC;
- $this->user = $DIC->user();
- $this->access = $DIC->access();
- }
+ $this->user = $DIC->user();
+ $this->access = $DIC->access();
+ }
- /**
- * get commands
- *
- * this method returns an array of all possible commands/permission combinations
- *
- * example:
- * $commands = array
- * (
- * array("permission" => "read", "cmd" => "view", "lang_var" => "show"),
- * array("permission" => "write", "cmd" => "edit", "lang_var" => "edit"),
- * );
- */
- static function _getCommands()
- {
- $commands = array
- (
- array("permission" => "read", "cmd" => "preview", "lang_var" => "show", "default" => true),
- array("permission" => "write", "cmd" => "render", "lang_var" => "edit"),
- array("permission" => "contribute", "cmd" => "render", "lang_var" => "edit"),
- array("permission" => "write", "cmd" => "edit", "lang_var" => "settings"),
- array("permission" => "write", "cmd" => "export", "lang_var" => "export_html")
- );
-
- return $commands;
- }
-
- /**
- * check whether goto script will succeed
- */
- static function _checkGoto($a_target)
- {
- global $DIC;
+ /**
+ * get commands
+ *
+ * this method returns an array of all possible commands/permission combinations
+ *
+ * example:
+ * $commands = array
+ * (
+ * array("permission" => "read", "cmd" => "view", "lang_var" => "show"),
+ * array("permission" => "write", "cmd" => "edit", "lang_var" => "edit"),
+ * );
+ */
+ public static function _getCommands()
+ {
+ $commands = array(
+ array("permission" => "read", "cmd" => "preview", "lang_var" => "show", "default" => true),
+ array("permission" => "write", "cmd" => "render", "lang_var" => "edit"),
+ array("permission" => "contribute", "cmd" => "render", "lang_var" => "edit"),
+ array("permission" => "write", "cmd" => "edit", "lang_var" => "settings"),
+ array("permission" => "write", "cmd" => "export", "lang_var" => "export_html")
+ );
+
+ return $commands;
+ }
+
+ /**
+ * check whether goto script will succeed
+ */
+ public static function _checkGoto($a_target)
+ {
+ global $DIC;
- $ilAccess = $DIC->access();
-
- $t_arr = explode("_", $a_target);
-
- if(substr($a_target, -3) == "wsp")
- {
- include_once "Services/PersonalWorkspace/classes/class.ilSharedResourceGUI.php";
- return ilSharedResourceGUI::hasAccess($t_arr[1]);
- }
-
- if ($t_arr[0] != "blog" || ((int) $t_arr[1]) <= 0)
- {
- return false;
- }
+ $ilAccess = $DIC->access();
+
+ $t_arr = explode("_", $a_target);
+
+ if (substr($a_target, -3) == "wsp") {
+ include_once "Services/PersonalWorkspace/classes/class.ilSharedResourceGUI.php";
+ return ilSharedResourceGUI::hasAccess($t_arr[1]);
+ }
+
+ if ($t_arr[0] != "blog" || ((int) $t_arr[1]) <= 0) {
+ return false;
+ }
- // #12648
- if ($ilAccess->checkAccess("read", "", $t_arr[1]))
- {
- return true;
- }
- return false;
- }
+ // #12648
+ if ($ilAccess->checkAccess("read", "", $t_arr[1])) {
+ return true;
+ }
+ return false;
+ }
- /**
- * @param ilWACPath $ilWACPath
- *
- * @return bool
- */
- public function canBeDelivered(ilWACPath $ilWACPath) {
- $ilUser = $this->user;
- $ilAccess = $this->access;
-
- if(preg_match("/\\/blog_([\\d]*)\\//uism", $ilWACPath->getPath(), $results))
- {
- $obj_id = $results[1];
-
- // personal workspace
- include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php";
- $tree = new ilWorkspaceTree(0);
- $node_id = $tree->lookupNodeId($obj_id);
- if($node_id)
- {
- include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php";
- $access_handler = new ilWorkspaceAccessHandler($tree);
- if ($access_handler->checkAccessOfUser($tree, $ilUser->getId(), "read", "view", $node_id, "blog")) {
- return true;
- }
- }
- // repository (RBAC)
- else
- {
- $ref_ids = ilObject::_getAllReferences($obj_id);
- foreach($ref_ids as $ref_id)
- {
- if ($ilAccess->checkAccessOfUser($ilUser->getId(), "read", "view", $ref_id, "blog", $obj_id))
- {
- return true;
- }
- }
- }
- }
+ /**
+ * @param ilWACPath $ilWACPath
+ *
+ * @return bool
+ */
+ public function canBeDelivered(ilWACPath $ilWACPath)
+ {
+ $ilUser = $this->user;
+ $ilAccess = $this->access;
+
+ if (preg_match("/\\/blog_([\\d]*)\\//uism", $ilWACPath->getPath(), $results)) {
+ $obj_id = $results[1];
+
+ // personal workspace
+ include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php";
+ $tree = new ilWorkspaceTree(0);
+ $node_id = $tree->lookupNodeId($obj_id);
+ if ($node_id) {
+ include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php";
+ $access_handler = new ilWorkspaceAccessHandler($tree);
+ if ($access_handler->checkAccessOfUser($tree, $ilUser->getId(), "read", "view", $node_id, "blog")) {
+ return true;
+ }
+ }
+ // repository (RBAC)
+ else {
+ $ref_ids = ilObject::_getAllReferences($obj_id);
+ foreach ($ref_ids as $ref_id) {
+ if ($ilAccess->checkAccessOfUser($ilUser->getId(), "read", "view", $ref_id, "blog", $obj_id)) {
+ return true;
+ }
+ }
+ }
+ }
- return false;
- }
+ return false;
+ }
}
-
-?>
diff --git a/Modules/Blog/classes/class.ilObjBlogAdministration.php b/Modules/Blog/classes/class.ilObjBlogAdministration.php
index 0fefe75a7d9619fecedca053e228af3d660947aa..26120d082571def2700dfb57ce7b85faf9a13f6f 100644
--- a/Modules/Blog/classes/class.ilObjBlogAdministration.php
+++ b/Modules/Blog/classes/class.ilObjBlogAdministration.php
@@ -3,7 +3,7 @@
/**
* Class ilObjBlogAdministration
-*
+*
* @author Jörg Lützenkirchen '.
- '
", $info));
- }
- else
- {
- ilUtil::sendInfo(implode("
", $info));
- }
- }
- // revert to edit cmd to avoid confusion
- $this->addHeaderActionForCommand("render");
- $tpl->setContent($ret);
- $nav = $this->renderNavigation($this->items, "render", $cmd, null, $is_owner);
- $tpl->setRightContent($nav);
- break;
- }
- }
- break;
-
- case "ilinfoscreengui":
- $this->prepareOutput();
- $this->addHeaderActionForCommand("render");
- $this->infoScreenForward();
- break;
-
- case "ilnotegui":
- $this->preview();
- break;
-
- case "ilcommonactiondispatchergui":
- include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php");
- $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall();
- $this->ctrl->forwardCommand($gui);
- break;
-
- case "ilpermissiongui":
- $this->prepareOutput();
- $ilTabs->activateTab("id_permissions");
- include_once("Services/AccessControl/classes/class.ilPermissionGUI.php");
- $perm_gui = new ilPermissionGUI($this);
- $this->ctrl->forwardCommand($perm_gui);
- break;
-
- case "ilobjectcopygui":
- $this->prepareOutput();
- include_once "./Services/Object/classes/class.ilObjectCopyGUI.php";
- $cp = new ilObjectCopyGUI($this);
- $cp->setType("blog");
- $this->ctrl->forwardCommand($cp);
- break;
-
- case 'ilrepositorysearchgui':
- $this->prepareOutput();
- $ilTabs->activateTab("contributors");
- include_once('./Services/Search/classes/class.ilRepositorySearchGUI.php');
- $rep_search = new ilRepositorySearchGUI();
- $rep_search->setTitle($this->lng->txt("blog_add_contributor"));
- $rep_search->setCallback($this,'addContributor',$this->object->getAllLocalRoles($this->node_id));
- $this->ctrl->setReturn($this,'contributors');
- $ret =& $this->ctrl->forwardCommand($rep_search);
- break;
-
- case 'ilexportgui':
- $this->prepareOutput();
- $ilTabs->activateTab("export");
- include_once("./Services/Export/classes/class.ilExportGUI.php");
- $exp_gui = new ilExportGUI($this);
- $exp_gui->addFormat("xml");
- $exp_gui->addFormat("html", null, $this, "buildExportFile"); // #13419
- $ret = $ilCtrl->forwardCommand($exp_gui);
- break;
-
- case "ilobjstylesheetgui":
- include_once ("./Services/Style/Content/classes/class.ilObjStyleSheetGUI.php");
- $this->ctrl->setReturn($this, "editStyleProperties");
- $style_gui = new ilObjStyleSheetGUI("", $this->object->getStyleSheetId(), false, false);
- $style_gui->omitLocator();
- if ($cmd == "create" || $this->new_type == "sty")
- {
- $style_gui->setCreationMode(true);
- }
-
- if ($cmd == "confirmedDelete")
- {
- $this->object->setStyleSheetId(0);
- $this->object->update();
- }
-
- $ret = $this->ctrl->forwardCommand($style_gui);
-
- if ($cmd == "save" || $cmd == "copyStyle" || $cmd == "importStyle")
- {
- $style_id = $ret;
- $this->object->setStyleSheetId($style_id);
- $this->object->update();
- $this->ctrl->redirectByClass("ilobjstylesheetgui", "edit");
- }
- break;
-
- case "ilblogexercisegui":
- $this->ctrl->setReturn($this, "render");
- include_once "Modules/Blog/classes/class.ilBlogExerciseGUI.php";
- $gui = new ilBlogExerciseGUI($this->node_id);
- $this->ctrl->forwardCommand($gui);
- break;
-
- case 'ilobjnotificationsettingsgui':
- $this->prepareOutput();
- $ilTabs->activateTab("settings");
- $this->setSettingsSubTabs("notifications");
- include_once("./Services/Notification/classes/class.ilObjNotificationSettingsGUI.php");
- $gui = new ilObjNotificationSettingsGUI($this->object->getRefId());
- $this->ctrl->forwardCommand($gui);
- break;
-
- default:
- if($cmd != "gethtml")
- {
- // desktop item handling, must be toggled before header action
- if($cmd == "addToDesk" || $cmd == "removeFromDesk")
- {
- $this->{$cmd."Object"}();
- if ($this->prvm)
- {
- $cmd = "preview";
- }
- else
- {
- $cmd = "render";
- }
- $ilCtrl->setCmd($cmd);
- }
- $this->addHeaderActionForCommand($cmd);
- }
- if(!$this->prtf_embed)
- {
- return parent::executeCommand();
- }
- else
- {
- $this->setTabs();
-
- if(!$cmd)
- {
- $cmd = "render";
- }
- return $this->$cmd();
- }
- }
-
- return true;
- }
-
- /**
- * this one is called from the info button in the repository
- * not very nice to set cmdClass/Cmd manually, if everything
- * works through ilCtrl in the future this may be changed
- */
- function infoScreen()
- {
- $this->ctrl->setCmd("showSummary");
- $this->ctrl->setCmdClass("ilinfoscreengui");
- $this->infoScreenForward();
- }
-
- /**
- * show information screen
- */
- function infoScreenForward()
- {
- $ilTabs = $this->tabs;
-
- $ilTabs->activateTab("id_info");
-
- $this->checkPermission("visible");
-
- include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php");
- $info = new ilInfoScreenGUI($this);
-
- if($this->id_type != self::WORKSPACE_NODE_ID)
- {
- $info->enablePrivateNotes();
- }
-
- if ($this->checkPermissionBool("read"))
- {
- $info->enableNews();
- }
-
- // no news editing for files, just notifications
- $info->enableNewsEditing(false);
- if ($this->checkPermissionBool("write"))
- {
- $news_set = new ilSetting("news");
- $enable_internal_rss = $news_set->get("enable_rss_for_internal");
-
- if ($enable_internal_rss)
- {
- $info->setBlockProperty("news", "settings", true);
- $info->setBlockProperty("news", "public_notifications_option", true);
- }
- }
-
- // standard meta data
- $info->addMetaDataSections($this->object->getId(), 0, $this->object->getType());
-
- if($this->id_type == self::WORKSPACE_NODE_ID)
- {
- $info->addProperty($this->lng->txt("perma_link"), $this->getPermanentLinkWidget());
- }
-
- $this->ctrl->forwardCommand($info);
- }
-
- /**
- * Create new posting
- */
- function createPosting()
- {
- $ilCtrl = $this->ctrl;
- $ilUser = $this->user;
-
- $title = trim(ilUtil::stripSlashes($_POST["title"]));
- if($title)
- {
- // create new posting
- include_once("./Modules/Blog/classes/class.ilBlogPosting.php");
- $posting = new ilBlogPosting();
- $posting->setTitle($title);
- $posting->setBlogId($this->object->getId());
- $posting->setActive(false);
- $posting->setAuthor($ilUser->getId());
- $posting->create();
-
- // switch month list to current month (will include new posting)
- $ilCtrl->setParameter($this, "bmn", date("Y-m"));
-
- $ilCtrl->setParameterByClass("ilblogpostinggui", "blpg", $posting->getId());
- $ilCtrl->redirectByClass("ilblogpostinggui", "edit");
- }
- else
- {
- ilUtil::sendFailure($this->lng->txt("msg_no_title"), true);
- $ilCtrl->redirect($this, "render");
- }
- }
-
- // --- ObjectGUI End
-
-
- /**
- * Render object context
- */
- function render()
- {
- $tpl = $this->tpl;
- $ilTabs = $this->tabs;
- $ilCtrl = $this->ctrl;
- $lng = $this->lng;
- $ilToolbar = new ilToolbarGUI();
- $ilUser = $this->user;
- $tree = $this->tree;
-
- if(!$this->checkPermissionBool("read"))
- {
- ilUtil::sendInfo($lng->txt("no_permission"));
- return;
- }
-
- $ilTabs->activateTab("content");
-
- // toolbar
- if($this->mayContribute())
- {
- $ilToolbar->setFormAction($ilCtrl->getFormAction($this, "createPosting"));
-
- include_once "Services/Form/classes/class.ilPropertyFormGUI.php";
- $title = new ilTextInputGUI($lng->txt("title"), "title");
- $ilToolbar->addStickyItem($title, $lng->txt("title"));
-
- include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php";
- $button = ilSubmitButton::getInstance();
- $button->setCaption("blog_add_posting");
- $button->setCommand("createPosting");
- $ilToolbar->addStickyItem($button);
-
- // #18763
- $first = array_shift((array_keys($this->items)));
- if($first != $this->month)
- {
- $ilToolbar->addSeparator();
-
- $ilCtrl->setParameter($this, "bmn", $first);
- $url = $ilCtrl->getLinkTarget($this, "");
- $ilCtrl->setParameter($this, "bmn", $this->month);
-
- include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php";
- $button = ilLinkButton::getInstance();
- $button->setCaption("blog_show_latest");
- $button->setUrl($url);
- $ilToolbar->addButtonInstance($button);
- }
-
- // exercise blog?
- include_once "Modules/Blog/classes/class.ilBlogExerciseGUI.php";
- $message = ilBlogExerciseGUI::checkExercise($this->node_id);
- }
-
- // $is_owner = ($this->object->getOwner() == $ilUser->getId());
- $is_owner = $this->mayContribute();
-
- $list_items = $this->getListItems($is_owner);
-
- $list = $nav = "";
- if($list_items)
- {
- $list = $this->renderList($list_items, "preview", null, $is_owner);
- $nav = $this->renderNavigation($this->items, "render", "preview", null, $is_owner);
- }
-
- $this->setContentStyleSheet();
-
- $tpl->setContent($message.$ilToolbar->getHTML().$list);
- $tpl->setRightContent($nav);
- }
-
- /**
- * Return embeddable HTML chunk
- *
- * @return string
- */
- function getHTML()
- {
- $ilUser = $this->user;
- $ilCtrl = $this->ctrl;
- $lng = $this->lng;
-
- // getHTML() is called by ilRepositoryGUI::show()
- if($this->id_type == self::REPOSITORY_NODE_ID)
- {
- return;
- }
-
- // there is no way to do a permissions check here, we have no wsp
-
- $this->filterInactivePostings();
-
- $list_items = $this->getListItems();
-
- $list = $nav = "";
- if($list_items)
- {
- $list = $this->renderList($list_items, "previewEmbedded");
- $nav = $this->renderNavigation($this->items, "gethtml", "previewEmbedded");
- }
- // quick editing in portfolio
- else if($this->prt_id)
- {
- // see renderList()
- if(ilObject::_lookupOwner($this->prt_id) == $ilUser->getId())
- {
- // see ilPortfolioPageTableGUI::fillRow()
- $ilCtrl->setParameterByClass("ilportfoliopagegui", "ppage", $this->user_page);
- $link = $ilCtrl->getLinkTargetByClass(array("ilportfoliopagegui", "ilobjbloggui"), "render");
- $ilCtrl->setParameterByClass("ilportfoliopagegui", "ppage", "");
-
- include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php";
- $btn = ilLinkButton::getInstance();
- $btn->setCaption(sprintf($lng->txt("prtf_edit_embedded_blog"), $this->object->getTitle()), false);
- $btn->setUrl($link);
- $btn->setPrimary(true);
-
- $list = $btn->render();
- }
- }
-
- return $this->buildEmbedded($list, $nav);
- }
-
- /**
- * Filter blog postings by month, keyword or author
- *
- * @param bool $a_show_inactive
- * @return array
- */
- protected function getListItems($a_show_inactive = false)
- {
- if($this->author)
- {
- $list_items = array();
- foreach($this->items as $month => $items)
- {
- foreach($items as $id => $item)
- {
- if($item["author"] == $this->author ||
- (is_array($item["editors"]) && in_array($this->author, $item["editors"])))
- {
- $list_items[$id] = $item;
- }
- }
- }
- }
- else if($this->keyword)
- {
- $list_items = $this->filterItemsByKeyword($this->items, $this->keyword);
- }
- else
- {
- $max = $this->object->getOverviewPostings();
- if($this->month_default && $max)
- {
- $list_items = array();
- foreach($this->items as $month => $postings)
- {
- foreach($postings as $id => $item)
- {
- if(!$a_show_inactive &&
- !ilBlogPosting::_lookupActive($id, "blp"))
- {
- continue;
- }
- $list_items[$id] = $item;
-
- if(sizeof($list_items) >= $max)
- {
- break(2);
- }
- }
- }
- }
- else
- {
- $list_items = $this->items[$this->month];
- }
- }
- return $list_items;
- }
-
- /**
- * Render fullscreen presentation
- */
- function preview()
- {
- global $DIC;
-
- $lng = $DIC->language();
- $toolbar = $DIC->toolbar();
-
- if(!$this->checkPermissionBool("read"))
- {
- ilUtil::sendInfo($lng->txt("no_permission"));
- return;
- }
-
- $this->filterInactivePostings();
-
- $list_items = $this->getListItems();
-
- $list = $nav = "";
- if($list_items)
- {
- $list = $this->renderList($list_items, "previewFullscreen");
- $nav = $this->renderNavigation($this->items, "preview", "previewFullscreen");
- $this->renderToolbarNavigation($this->items);
- $list.= $toolbar->getHTML();
- }
-
- $this->renderFullScreen($list, $nav);
- }
-
- /**
- * Build and deliver export file
- */
- function export()
- {
- $zip = $this->buildExportFile();
-
- ilUtil::deliverFile($zip, $this->object->getTitle().".zip", '', false, true);
- }
-
-
- // --- helper functions
-
- /**
- * Combine content (list/posting) and navigation to html chunk
- *
- * @param string $a_content
- * @param string $a_nav
- * @return string
- */
- protected function buildEmbedded($a_content, $a_nav)
- {
- $wtpl = new ilTemplate("tpl.blog_embedded.html", true, true, "Modules/Blog");
- $wtpl->setVariable("VAL_LIST", $a_content);
- $wtpl->setVariable("VAL_NAVIGATION", $a_nav);
- return $wtpl->get();
- }
-
- /**
- * Build fullscreen context
- *
- * @param string $a_content
- * @param string $a_navigation
- */
- function renderFullScreen($a_content, $a_navigation)
- {
- $tpl = $this->tpl;
- $ilUser = $this->user;
- $ilTabs = $this->tabs;
- $ilLocator = $this->locator;
-
- $owner = $this->object->getOwner();
-
- $ilTabs->clearTargets();
- $ilLocator->clearItems();
- $tpl->setLocator();
-
- $back_caption = "";
-
- // back (edit)
- if($owner == $ilUser->getId())
- {
- // from shared/deeplink
- if($this->id_type == self::WORKSPACE_NODE_ID)
- {
- $back = "ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToWorkspace&wsp_id=".$this->node_id;
- }
- // from editor (#10073)
- else if($this->mayContribute())
- {
- $this->ctrl->setParameter($this, "prvm", "");
- if($this->blpg == 0)
- {
- $back = $this->ctrl->getLinkTarget($this, "");
- }
- else
- {
- $this->ctrl->setParameterByClass("ilblogpostinggui", "bmn", $this->month);
- $this->ctrl->setParameterByClass("ilblogpostinggui", "blpg", $this->blpg);
- $back = $this->ctrl->getLinkTargetByClass("ilblogpostinggui", "preview");
- }
- $this->ctrl->setParameter($this, "prvm", $this->prvm);
- }
-
- $back_caption = $this->lng->txt("blog_back_to_blog_owner");
- }
- // back
- else if($ilUser->getId() && $ilUser->getId() != ANONYMOUS_USER_ID)
- {
- // workspace (always shared)
- if($this->id_type == self::WORKSPACE_NODE_ID)
- {
- $back = "ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToWorkspace&dsh=".$owner;
- }
- // contributor
- else if($this->mayContribute())
- {
- $back = $this->ctrl->getLinkTarget($this, "");
- $back_caption = $this->lng->txt("blog_back_to_blog_owner");
- }
- // listgui / parent container
- else
- {
- $tree = $this->tree;
- $parent_id = $tree->getParentId($this->node_id);
- include_once "Services/Link/classes/class.ilLink.php";
- $back = ilLink::_getStaticLink($parent_id);
- }
- }
-
- $ilMainMenu = $this->main_menu;
- $ilMainMenu->setMode(ilMainMenuGUI::MODE_TOPBAR_ONLY);
- $ilMainMenu->setTopBarBack($back, $back_caption);
-
- $this->renderFullscreenHeader($tpl, $owner);
-
- // #13564
- $this->ctrl->setParameter($this, "bmn", "");
- $tpl->setTitleUrl($this->ctrl->getLinkTarget($this, "preview"));
- $this->ctrl->setParameter($this, "bmn", $this->month);
-
- $this->setContentStyleSheet();
-
- // content
- $tpl->setContent($a_content);
- $tpl->setRightContent($a_navigation);
- }
-
- /**
- * Render banner, user name
- *
- * @param object $a_tpl
- * @param int $a_user_id
- * @param bool $a_export_path
- */
- protected function renderFullscreenHeader($a_tpl, $a_user_id, $a_export = false)
- {
- $ilUser = $this->user;
-
- if(!$a_export)
- {
- require_once('Services/Tracking/classes/class.ilChangeEvent.php');
- ilChangeEvent::_recordReadEvent(
- $this->object->getType(),
- $this->node_id,
- $this->object->getId(),
- $ilUser->getId()
- );
- }
-
- // repository blogs are multi-author
- $name = null;
- if($this->id_type != self::REPOSITORY_NODE_ID)
- {
- $name = ilObjUser::_lookupName($a_user_id);
- $name = $name["lastname"].", ".($t = $name["title"] ? $t . " " : "").$name["firstname"];
- }
-
- // show banner?
- $banner = false;
- $blga_set = new ilSetting("blga");
- if($blga_set->get("banner"))
- {
- require_once('./Services/WebAccessChecker/classes/class.ilWACSignedPath.php');
- $banner = ilWACSignedPath::signFile($this->object->getImageFullPath());
- $banner_width = $blga_set->get("banner_width");
- $banner_height = $blga_set->get("banner_height");
- if($a_export)
- {
- $banner = basename($banner);
- }
- }
-
- $ppic = null;
- if($this->object->hasProfilePicture())
- {
- // repository (multi-user)
- if($this->id_type == self::REPOSITORY_NODE_ID)
- {
- // #15030
- if($this->blpg > 0 && !$a_export)
- {
- include_once "Modules/Blog/classes/class.ilBlogPosting.php";
- $post = new ilBlogPosting($this->blpg);
- $author_id = $post->getAuthor();
- if($author_id)
- {
- $ppic = ilObjUser::_getPersonalPicturePath($author_id, "xsmall", true, true);
-
- $name = ilObjUser::_lookupName($author_id);
- $name = $name["lastname"].", ".($t = $name["title"] ? $t . " " : "").$name["firstname"];
- }
- }
- }
- // workspace (author == owner)
- else
- {
- $ppic = ilObjUser::_getPersonalPicturePath($a_user_id, "xsmall", true, true);
- if($a_export)
- {
- $ppic = basename($ppic);
- }
- }
- }
-
- $a_tpl->resetHeaderBlock(false);
- // $a_tpl->setBackgroundColor($this->object->getBackgroundColor());
- $a_tpl->setBanner($banner, $banner_width, $banner_height, $a_export);
- $a_tpl->setTitleIcon($ppic);
- $a_tpl->setTitle($this->object->getTitle());
- // $a_tpl->setTitleColor($this->object->getFontColor());
- $a_tpl->setDescription($name);
-
- // to get rid of locator in repository preview
- $a_tpl->setVariable("LOCATOR", "");
-
- // :TODO: obsolete?
- // $a_tpl->setBodyClass("std ilExternal ilBlog");
- }
-
- /**
- * Gather all blog postings
- *
- * @param int $a_obj_id
- * @return array
- */
- protected function buildPostingList($a_obj_id)
- {
- $author_found = false;
-
- $items = array();
- foreach(ilBlogPosting::getAllPostings($a_obj_id) as $posting)
- {
- if($this->author &&
- ($posting["author"] == $this->author ||
- (is_array($posting["editors"]) && in_array($this->author, $posting["editors"]))))
- {
- $author_found = true;
- }
-
- $month = substr($posting["created"]->get(IL_CAL_DATE), 0, 7);
- $items[$month][$posting["id"]] = $posting;
- }
-
- if($this->author && !$author_found)
- {
- $this->author = null;
- }
-
- return $items;
- }
-
- /**
- * Build posting month list
- *
- * @param array $items
- * @param string $a_cmd
- * @param bool $a_link_template
- * @param bool $a_show_inactive
- * @param string $a_export_directory
- * @return string
- */
- function renderList(array $items, $a_cmd = "preview", $a_link_template = null, $a_show_inactive = false, $a_export_directory = null)
- {
- $lng = $this->lng;
- $ilCtrl = $this->ctrl;
- $ilUser = $this->user;
-
- include_once "Services/Calendar/classes/class.ilCalendarUtil.php";
- $wtpl = new ilTemplate("tpl.blog_list.html", true, true, "Modules/Blog");
-
- // quick editing in portfolio
- if ($this->prt_id > 0 &&
- stristr($a_cmd, "embedded"))
- {
- if(ilObject::_lookupOwner($this->prt_id) == $ilUser->getId())
- {
- // see ilPortfolioPageTableGUI::fillRow()
- $ilCtrl->setParameterByClass("ilportfoliopagegui", "ppage", $this->user_page);
- $link = $ilCtrl->getLinkTargetByClass(array("ilportfoliopagegui", "ilobjbloggui"), "render");
- $ilCtrl->setParameterByClass("ilportfoliopagegui", "ppage", "");
-
- include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php";
- $list = new ilAdvancedSelectionListGUI();
- $list->setListTitle($lng->txt("action"));
- $list->addItem(
- sprintf($lng->txt("prtf_edit_embedded_blog"), $this->object->getTitle()),
- "",
- $link);
-
- /*
- include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php";
- $btn = ilLinkButton::getInstance();
- $btn->setCaption(sprintf($lng->txt("prtf_edit_embedded_blog"), $this->object->getTitle()), false);
- $btn->setUrl($link);
- */
-
- $wtpl->setCurrentBlock("prtf_edit_bl");
- $wtpl->setVariable("PRTF_BLOG_EDIT", $list->getHTML());
- $wtpl->parseCurrentBlock();
- }
- }
-
- $is_admin = $this->isAdmin();
-
- include_once("./Modules/Blog/classes/class.ilBlogPostingGUI.php");
- $last_month = null;
- $is_empty = true;
- foreach($items as $item)
- {
- // only published items
- $is_active = ilBlogPosting::_lookupActive($item["id"], "blp");
- if(!$is_active && !$a_show_inactive)
- {
- continue;
- }
-
- $is_empty = false;
-
- if(!$this->keyword && !$this->author)
- {
- $month = substr($item["created"]->get(IL_CAL_DATE), 0, 7);
- }
-
- if(!$last_month || $last_month != $month)
- {
- if($last_month)
- {
- $wtpl->setCurrentBlock("month_bl");
- $wtpl->parseCurrentBlock();
- }
-
- // title according to current "filter"/navigation
- if($this->keyword)
- {
- $title = $lng->txt("blog_keyword").": ".$this->keyword;
- }
- else if($this->author)
- {
- include_once "Services/User/classes/class.ilUserUtil.php";
- $title = $lng->txt("blog_author").": ".ilUserUtil::getNamePresentation($this->author);
- }
- else
- {
- include_once "Services/Calendar/classes/class.ilCalendarUtil.php";
- $title = ilCalendarUtil::_numericMonthToString((int)substr($month, 5)).
- " ".substr($month, 0, 4);
-
- $last_month = $month;
- }
-
- $wtpl->setVariable("TXT_CURRENT_MONTH", $title);
- }
-
- if(!$a_link_template)
- {
- $ilCtrl->setParameterByClass("ilblogpostinggui", "bmn", $this->month);
- $ilCtrl->setParameterByClass("ilblogpostinggui", "blpg", $item["id"]);
- $preview = $ilCtrl->getLinkTargetByClass("ilblogpostinggui", $a_cmd);
- }
- else
- {
- $preview = $this->buildExportLink($a_link_template, "posting", $item["id"]);
- }
-
- // actions
- $posting_edit = $this->mayEditPosting($item["id"], $item["author"]);
- if(($posting_edit || $is_admin) && !$a_link_template && $a_cmd == "preview")
- {
- include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php");
- $alist = new ilAdvancedSelectionListGUI();
- $alist->setId($item["id"]);
- $alist->setListTitle($lng->txt("actions"));
-
- if($is_active && $this->object->hasApproval() && !$item["approved"])
- {
- if($is_admin)
- {
- $ilCtrl->setParameter($this, "apid", $item["id"]);
- $alist->addItem($lng->txt("blog_approve"), "approve",
- $ilCtrl->getLinkTarget($this, "approve"));
- $ilCtrl->setParameter($this, "apid", "");
- }
-
- $wtpl->setVariable("APPROVAL", $lng->txt("blog_needs_approval"));
- }
-
- if($posting_edit)
- {
- $alist->addItem($lng->txt("edit_content"), "edit",
- $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "edit"));
-
- // #11858
- if($is_active)
- {
- $alist->addItem($lng->txt("blog_toggle_draft"), "deactivate",
- $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "deactivatePageToList"));
- }
- else
- {
- $alist->addItem($lng->txt("blog_toggle_final"), "activate",
- $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "activatePageToList"));
- }
-
- $alist->addItem($lng->txt("rename"), "rename",
- $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "edittitle"));
-
- if($this->object->hasKeywords()) // #13616
- {
- $alist->addItem($lng->txt("blog_edit_keywords"), "keywords",
- $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "editKeywords"));
- }
-
- $alist->addItem($lng->txt("blog_edit_date"), "editdate",
- $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "editdate"));
- $alist->addItem($lng->txt("delete"), "delete",
- $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "deleteBlogPostingConfirmationScreen"));
- }
- else if($is_admin)
- {
- // #10513
- if($is_active)
- {
- $ilCtrl->setParameter($this, "apid", $item["id"]);
- $alist->addItem($lng->txt("blog_toggle_draft_admin"), "deactivate",
- $ilCtrl->getLinkTarget($this, "deactivateAdmin"));
- $ilCtrl->setParameter($this, "apid", "");
- }
-
- $alist->addItem($lng->txt("delete"), "delete",
- $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "deleteBlogPostingConfirmationScreen"));
- }
-
- $wtpl->setCurrentBlock("actions");
- $wtpl->setVariable("ACTION_SELECTOR", $alist->getHTML());
- $wtpl->parseCurrentBlock();
- }
-
- // comments
- if($this->object->getNotesStatus() && !$a_link_template && !$this->disable_notes)
- {
- // count (public) notes
- include_once("Services/Notes/classes/class.ilNote.php");
- $count = sizeof(ilNote::_getNotesOfObject($this->obj_id,
- $item["id"], "blp", IL_NOTE_PUBLIC));
-
- if($a_cmd != "preview")
- {
- $wtpl->setCurrentBlock("comments");
- $wtpl->setVariable("TEXT_COMMENTS", $lng->txt("blog_comments"));
- $wtpl->setVariable("URL_COMMENTS", $preview);
- $wtpl->setVariable("COUNT_COMMENTS", $count);
- $wtpl->parseCurrentBlock();
- }
- /* we disabled comments in edit mode (should always be done via pagegui)
- else
- {
- $hash = ilCommonActionDispatcherGUI::buildAjaxHash(ilCommonActionDispatcherGUI::TYPE_WORKSPACE,
- $this->node_id, "blog", $this->obj_id, "blp", $item["id"]);
- $notes_link = "#\" onclick=\"".ilNoteGUI::getListCommentsJSCall($hash);
- }
- */
- }
-
- // permanent link
- if($a_cmd != "preview" && $a_cmd != "previewEmbedded")
- {
- if($this->id_type == self::WORKSPACE_NODE_ID)
- {
- $goto = $this->getAccessHandler()->getGotoLink($this->node_id, $this->obj_id, "_".$item["id"]);
- }
- else
- {
- include_once "Services/Link/classes/class.ilLink.php";
- $goto = ilLink::_getStaticLink($this->node_id, $this->getType(), true, "_".$item["id"]);
- }
- $wtpl->setCurrentBlock("permalink");
- $wtpl->setVariable("URL_PERMALINK", $goto);
- $wtpl->setVariable("TEXT_PERMALINK", $lng->txt("blog_permanent_link"));
- $wtpl->parseCurrentBlock();
- }
-
- $snippet = ilBlogPostingGUI::getSnippet($item["id"],
- $this->object->hasAbstractShorten(),
- $this->object->getAbstractShortenLength(),
- "…",
- $this->object->hasAbstractImage(),
- $this->object->getAbstractImageWidth(),
- $this->object->getAbstractImageHeight(),
- $a_export_directory);
-
- if($snippet)
- {
- $wtpl->setCurrentBlock("more");
- $wtpl->setVariable("URL_MORE", $preview);
- $wtpl->setVariable("TEXT_MORE", $lng->txt("blog_list_more"));
- $wtpl->parseCurrentBlock();
- }
-
-
-
- if(!$is_active)
- {
- $wtpl->setCurrentBlock("draft_text");
- $wtpl->setVariable("DRAFT_TEXT", $lng->txt("blog_draft_text"));
- $wtpl->parseCurrentBlock();
- $wtpl->setVariable("DRAFT_CLASS", " ilBlogListItemDraft");
- }
-
- $wtpl->setCurrentBlock("posting");
-
- $author = "";
- if($this->id_type == self::REPOSITORY_NODE_ID)
- {
- $authors = array();
-
- $author_id = $item["author"];
- if($author_id)
- {
- include_once "Services/User/classes/class.ilUserUtil.php";
- $authors[] = ilUserUtil::getNamePresentation($author_id);
- }
-
- if(is_array($item["editors"]))
- {
- foreach($item["editors"] as $editor_id)
- {
- $authors[] = ilUserUtil::getNamePresentation($editor_id);
- }
- }
-
- if($authors)
- {
- $author = implode(", ", $authors)." - ";
- }
- }
-
- // title
- $wtpl->setVariable("URL_TITLE", $preview);
- $wtpl->setVariable("TITLE", $item["title"]);
+ /**
+ * @var ilHelpGUI
+ */
+ protected $help;
+
+ /**
+ * @var ilTabsGUI
+ */
+ protected $tabs;
+
+ /**
+ * @var ilNavigationHistory
+ */
+ protected $nav_history;
+
+ /**
+ * @var ilMainMenuGUI
+ */
+ protected $main_menu;
+
+ /**
+ * @var ilRbacAdmin
+ */
+ protected $rbacadmin;
+
+ protected $month; // [string]
+ protected $items; // [array]
+ protected $keyword; // [string]
+ protected $author; // [int]
+ protected $month_default; // [bool]
+
+ /**
+ * Goto link posting
+ * @var int
+ */
+ protected $gtp;
+
+ /**
+ * @var int
+ */
+ protected $blpg;
+
+ /**
+ * @var int
+ */
+ protected $old_nr;
+
+ /**
+ * user page? deprecated?
+ * @var int
+ */
+ protected $ppage;
+
+ /**
+ * user page (necessary?)
+ * @var int
+ */
+ protected $user_page;
+
+ /**
+ * @var bool // note: this is currently set in ilPortfolioPageGUI, should use getter/setter
+ */
+ public $prtf_embed = false;
+
+ /**
+ * preview mode (fsc|emb)
+ *
+ * @var string
+ */
+ protected $prvm;
+
+ /**
+ * @var int
+ */
+ protected $ntf;
+
+ /**
+ * approved posting id
+ * @var int
+ */
+ protected $apid;
+
+ /**
+ * @var string
+ */
+ protected $new_type;
+
+ /**
+ * portfolio id (quick editing in portfolio)
+ * @var int
+ */
+ protected $prt_id;
+
+ protected static $keyword_export_map; // [array]
+
+ public function __construct($a_id = 0, $a_id_type = self::REPOSITORY_NODE_ID, $a_parent_node_id = 0)
+ {
+ global $DIC;
+
+ $this->settings = $DIC->settings();
+ $this->help = $DIC["ilHelp"];
+ $this->tabs = $DIC->tabs();
+ $this->nav_history = $DIC["ilNavigationHistory"];
+ $this->user = $DIC->user();
+ $this->toolbar = $DIC->toolbar();
+ $this->tree = $DIC->repositoryTree();
+ $this->locator = $DIC["ilLocator"];
+ $this->main_menu = $DIC["ilMainMenu"];
+ $this->rbacreview = $DIC->rbac()->review();
+ $this->rbacadmin = $DIC->rbac()->admin();
+
+ $lng = $DIC->language();
+ $ilCtrl = $DIC->ctrl();
+
+ $this->gtp = (int) $_GET["gtp"];
+ $this->blpg = (int) $_REQUEST["blpg"];
+ $this->old_nr = (int) $_GET["old_nr"];
+ $this->ppage = (int) $_GET["ppage"];
+ $this->user_page = (int) $_REQUEST["user_page"];
+ $this->new_type = ilUtil::stripSlashes($_REQUEST["new_type"]);
+ $this->prvm = ilUtil::stripSlashes($_REQUEST["prvm"]);
+ $this->ntf = (int) $_GET["ntf"];
+ $this->apid = (int) $_GET["apid"];
+ $this->month = ilUtil::stripSlashes($_REQUEST["bmn"]);
+ $this->keyword = ilUtil::stripSlashes($_REQUEST["kwd"]);
+ $this->author = (int) $_REQUEST["ath"];
+ $this->prt_id = (int) $_REQUEST["prt_id"];
+
+ parent::__construct($a_id, $a_id_type, $a_parent_node_id);
+
+ if ($_REQUEST["blpg"] > 0 && ilBlogPosting::lookupBlogId($_REQUEST["blpg"]) != $this->object->getId()) {
+ throw new ilException("Posting ID does not match blog.");
+ }
+
+ if ($this->object) {
+ // gather postings by month
+ $this->items = $this->buildPostingList($this->object->getId());
+ if ($this->items) {
+ // current month (if none given or empty)
+ if (!$this->month || !$this->items[$this->month]) {
+ $this->month = array_keys($this->items);
+ $this->month = array_shift($this->month);
+ $this->month_default = true;
+ }
+ }
+
+ $ilCtrl->setParameter($this, "bmn", $this->month);
+ }
+
+ $lng->loadLanguageModule("blog");
+ $ilCtrl->saveParameter($this, "prvm");
+ }
+
+ public function getType()
+ {
+ return "blog";
+ }
+
+ protected function initCreationForms($a_new_type)
+ {
+ $forms = parent::initCreationForms($a_new_type);
+
+ if ($this->id_type == self::WORKSPACE_NODE_ID) {
+ unset($forms[self::CFORM_IMPORT]);
+ unset($forms[self::CFORM_CLONE]);
+ }
+
+ return $forms;
+ }
+
+ protected function afterSave(ilObject $a_new_object)
+ {
+ $ilCtrl = $this->ctrl;
+
+ ilUtil::sendSuccess($this->lng->txt("object_added"), true);
+ $ilCtrl->redirect($this, "");
+ }
+
+ protected function setSettingsSubTabs($a_active)
+ {
+ global $DIC;
+
+ $tree = $DIC->repositoryTree();
+ $access = $DIC->access();
+
+ // general properties
+ $this->tabs_gui->addSubTab(
+ "properties",
+ $this->lng->txt("blog_properties"),
+ $this->ctrl->getLinkTarget($this, 'edit')
+ );
+
+ $this->tabs_gui->addSubTab(
+ "style",
+ $this->lng->txt("obj_sty"),
+ $this->ctrl->getLinkTarget($this, 'editStyleProperties')
+ );
+
+ // notification settings for blogs in courses and groups
+ if ($this->id_type == self::REPOSITORY_NODE_ID) {
+ $grp_ref_id = $tree->checkForParentType($this->object->getRefId(), 'grp');
+ $crs_ref_id = $tree->checkForParentType($this->object->getRefId(), 'crs');
+
+ if ((int) $grp_ref_id > 0 || (int) $crs_ref_id > 0) {
+ if ($access->checkAccess('write', '', $this->ref_id)) {
+ $this->tabs_gui->addSubTab(
+ 'notifications',
+ $this->lng->txt("notifications"),
+ $this->ctrl->getLinkTargetByClass("ilobjnotificationsettingsgui", '')
+ );
+ }
+ }
+ }
+
+ $this->tabs_gui->activateSubTab($a_active);
+ }
+
+ protected function initEditCustomForm(ilPropertyFormGUI $a_form)
+ {
+ $lng = $this->lng;
+ $ilSetting = $this->settings;
+ $obj_service = $this->getObjectService();
+
+ $this->setSettingsSubTabs("properties");
+
+ if ($this->id_type == self::REPOSITORY_NODE_ID) {
+ $appr = new ilCheckboxInputGUI($lng->txt("blog_enable_approval"), "approval");
+ $appr->setInfo($lng->txt("blog_enable_approval_info"));
+ $a_form->addItem($appr);
+ }
+
+ $notes = new ilCheckboxInputGUI($lng->txt("blog_enable_notes"), "notes");
+ $a_form->addItem($notes);
+
+ if ($ilSetting->get('enable_global_profiles')) {
+ $rss = new ilCheckboxInputGUI($lng->txt("blog_enable_rss"), "rss");
+ $rss->setInfo($lng->txt("blog_enable_rss_info"));
+ $a_form->addItem($rss);
+ }
+
+
+ // navigation
+
+ $nav = new ilFormSectionHeaderGUI();
+ $nav->setTitle($lng->txt("blog_settings_navigation"));
+ $a_form->addItem($nav);
+
+ $nav_mode = new ilRadioGroupInputGUI($lng->txt("blog_nav_mode"), "nav");
+ $nav_mode->setRequired(true);
+ $a_form->addItem($nav_mode);
+
+ $opt = new ilRadioOption($lng->txt("blog_nav_mode_month_list"), ilObjBlog::NAV_MODE_LIST);
+ $opt->setInfo($lng->txt("blog_nav_mode_month_list_info"));
+ $nav_mode->addOption($opt);
+
+
+ $mon_num = new ilNumberInputGUI($lng->txt("blog_nav_mode_month_list_num_month"), "nav_list_mon");
+ $mon_num->setInfo($lng->txt("blog_nav_mode_month_list_num_month_info"));
+ $mon_num->setSize(3);
+ $mon_num->setMinValue(1);
+ $opt->addSubItem($mon_num);
+
+ $detail_num = new ilNumberInputGUI($lng->txt("blog_nav_mode_month_list_num_month_with_post"), "nav_list_mon_with_post");
+ $detail_num->setInfo($lng->txt("blog_nav_mode_month_list_num_month_with_post_info"));
+ //$detail_num->setRequired(true);
+ $detail_num->setSize(3);
+ //$detail_num->setMinValue(0);
+ $opt->addSubItem($detail_num);
+
+ $opt = new ilRadioOption($lng->txt("blog_nav_mode_month_single"), ilObjBlog::NAV_MODE_MONTH);
+ $opt->setInfo($lng->txt("blog_nav_mode_month_single_info"));
+ $nav_mode->addOption($opt);
+
+ $order_options = array();
+ if ($this->object->getOrder()) {
+ foreach ($this->object->getOrder() as $item) {
+ $order_options[] = $lng->txt("blog_" . $item);
+ }
+ }
+
+ if (!in_array($lng->txt("blog_navigation"), $order_options)) {
+ $order_options[] = $lng->txt("blog_navigation");
+ }
+
+ if ($this->id_type == self::REPOSITORY_NODE_ID) {
+ if (!in_array($lng->txt("blog_authors"), $order_options)) {
+ $order_options[] = $lng->txt("blog_authors");
+ }
+
+ $auth = new ilCheckboxInputGUI($lng->txt("blog_enable_nav_authors"), "nav_authors");
+ $auth->setInfo($lng->txt("blog_enable_nav_authors_info"));
+ $a_form->addItem($auth);
+ }
+
+ $keyw = new ilCheckboxInputGUI($lng->txt("blog_enable_keywords"), "keywords");
+ $keyw->setInfo($lng->txt("blog_enable_keywords_info"));
+ $a_form->addItem($keyw);
+
+ if (!in_array($lng->txt("blog_keywords"), $order_options)) {
+ $order_options[] = $lng->txt("blog_keywords");
+ }
+
+ $order = new ilNonEditableValueGUI($lng->txt("blog_nav_sortorder"), "order");
+ $order->setMultiValues($order_options);
+ $order->setValue(array_shift($order_options));
+ $order->setMulti(true, true, false);
+ $a_form->addItem($order);
+
+
+ // presentation (frame)
+
+ $pres = new ilFormSectionHeaderGUI();
+ $pres->setTitle($lng->txt("blog_presentation_frame"));
+ $a_form->addItem($pres);
+
+ if ($this->id_type == self::REPOSITORY_NODE_ID) {
+ $obj_service->commonSettings()->legacyForm($a_form, $this->object)->addTileImage();
+ }
+
+ $ppic = new ilCheckboxInputGUI($lng->txt("blog_profile_picture"), "ppic");
+ $a_form->addItem($ppic);
+
+ if ($this->id_type == self::REPOSITORY_NODE_ID) {
+ $ppic->setInfo($lng->txt("blog_profile_picture_repository_info"));
+ }
+
+ $blga_set = new ilSetting("blga");
+ if ($blga_set->get("banner")) {
+ include_once "Services/Form/classes/class.ilFileInputGUI.php";
+ ilFileInputGUI::setPersonalWorkspaceQuotaCheck(true);
+
+ $dimensions = " (" . $blga_set->get("banner_width") . "x" .
+ $blga_set->get("banner_height") . ")";
+
+ $img = new ilImageFileInputGUI($lng->txt("blog_banner") . $dimensions, "banner");
+ $a_form->addItem($img);
+
+ // show existing file
+ $file = $this->object->getImageFullPath(true);
+ if ($file) {
+ $img->setImage($file);
+ }
+ }
+
+ /* #15000
+ $bg_color = new ilColorPickerInputGUI($lng->txt("blog_background_color"), "bg_color");
+ $a_form->addItem($bg_color);
+
+ $font_color = new ilColorPickerInputGUI($lng->txt("blog_font_color"), "font_color");
+ $a_form->addItem($font_color);
+ */
+
+ // presentation (overview)
+
+ $list = new ilFormSectionHeaderGUI();
+ $list->setTitle($lng->txt("blog_presentation_overview"));
+ $a_form->addItem($list);
+
+
+ $post_num = new ilNumberInputGUI($lng->txt("blog_list_num_postings"), "ov_list_post_num");
+ $post_num->setInfo($lng->txt("blog_list_num_postings_info"));
+ $post_num->setSize(3);
+ $post_num->setMinValue(1);
+ $post_num->setRequired(true);
+ $a_form->addItem($post_num);
+
+ $abs_shorten = new ilCheckboxInputGUI($lng->txt("blog_abstract_shorten"), "abss");
+ $a_form->addItem($abs_shorten);
+
+ $abs_shorten_len = new ilNumberInputGUI($lng->txt("blog_abstract_shorten_length"), "abssl");
+ $abs_shorten_len->setSize(5);
+ $abs_shorten_len->setRequired(true);
+ $abs_shorten_len->setSuffix($lng->txt("blog_abstract_shorten_characters"));
+ $abs_shorten_len->setMinValue(50, true);
+ $abs_shorten->addSubItem($abs_shorten_len);
+
+ $abs_img = new ilCheckboxInputGUI($lng->txt("blog_abstract_image"), "absi");
+ $abs_img->setInfo($lng->txt("blog_abstract_image_info"));
+ $a_form->addItem($abs_img);
+
+ $abs_img_width = new ilNumberInputGUI($lng->txt("blog_abstract_image_width"), "absiw");
+ $abs_img_width->setSize(5);
+ $abs_img_width->setRequired(true);
+ $abs_img_width->setSuffix($lng->txt("blog_abstract_image_pixels"));
+ $abs_img_width->setMinValue(32, true);
+ $abs_img->addSubItem($abs_img_width);
+
+ $abs_img_height = new ilNumberInputGUI($lng->txt("blog_abstract_image_height"), "absih");
+ $abs_img_height->setSize(5);
+ $abs_img_height->setRequired(true);
+ $abs_img_height->setSuffix($lng->txt("blog_abstract_image_pixels"));
+ $abs_img_height->setMinValue(32, true);
+ $abs_img->addSubItem($abs_img_height);
+ }
+
+ protected function getEditFormCustomValues(array &$a_values)
+ {
+ if ($this->id_type == self::REPOSITORY_NODE_ID) {
+ $a_values["approval"] = $this->object->hasApproval();
+ $a_values["nav_authors"] = $this->object->hasAuthors();
+ }
+ $a_values["keywords"] = $this->object->hasKeywords();
+ $a_values["notes"] = $this->object->getNotesStatus();
+ $a_values["ppic"] = $this->object->hasProfilePicture();
+ /*
+ $a_values["bg_color"] = $this->object->getBackgroundColor();
+ $a_values["font_color"] = $this->object->getFontColor();
+ */
+ $a_values["banner"] = $this->object->getImage();
+ $a_values["rss"] = $this->object->hasRSS();
+ $a_values["abss"] = $this->object->hasAbstractShorten();
+ $a_values["absi"] = $this->object->hasAbstractImage();
+ $a_values["nav"] = $this->object->getNavMode();
+ $a_values["nav_list_mon_with_post"] = $this->object->getNavModeListMonthsWithPostings();
+ $a_values["nav_list_mon"] = $this->object->getNavModeListMonths();
+ $a_values["ov_list_post_num"] = $this->object->getOverviewPostings();
+
+ // #13420
+ $a_values["abssl"] = $this->object->getAbstractShortenLength() ? $this->object->getAbstractShortenLength() : ilObjBlog::ABSTRACT_DEFAULT_SHORTEN_LENGTH;
+ $a_values["absiw"] = $this->object->getAbstractImageWidth() ? $this->object->getAbstractImageWidth() : ilObjBlog::ABSTRACT_DEFAULT_IMAGE_WIDTH;
+ $a_values["absih"] = $this->object->getAbstractImageHeight() ? $this->object->getAbstractImageHeight() : ilObjBlog::ABSTRACT_DEFAULT_IMAGE_HEIGHT;
+ }
+
+ protected function updateCustom(ilPropertyFormGUI $a_form)
+ {
+ $lng = $this->lng;
+ $obj_service = $this->getObjectService();
+
+ if ($this->id_type == self::REPOSITORY_NODE_ID) {
+ $this->object->setApproval($a_form->getInput("approval"));
+ $this->object->setAuthors($a_form->getInput("nav_authors"));
+ $obj_service->commonSettings()->legacyForm($a_form, $this->object)->saveTileImage();
+ }
+ $this->object->setKeywords($a_form->getInput("keywords"));
+ $this->object->setNotesStatus($a_form->getInput("notes"));
+ $this->object->setProfilePicture($a_form->getInput("ppic"));
+ /*
+ $this->object->setBackgroundColor($a_form->getInput("bg_color"));
+ $this->object->setFontColor($a_form->getInput("font_color"));
+ */
+ $this->object->setRSS($a_form->getInput("rss"));
+ $this->object->setAbstractShorten($a_form->getInput("abss"));
+ $this->object->setAbstractShortenLength($a_form->getInput("abssl"));
+ $this->object->setAbstractImage($a_form->getInput("absi"));
+ $this->object->setAbstractImageWidth($a_form->getInput("absiw"));
+ $this->object->setAbstractImageHeight($a_form->getInput("absih"));
+ $this->object->setNavMode($a_form->getInput("nav"));
+ $this->object->setNavModeListMonthsWithPostings($a_form->getInput("nav_list_mon_with_post"));
+ $this->object->setNavModeListMonths($a_form->getInput("nav_list_mon"));
+ $this->object->setOverviewPostings($a_form->getInput("ov_list_post_num"));
+
+ $order = $a_form->getInput("order");
+ foreach ($order as $idx => $value) {
+ if ($value == $lng->txt("blog_navigation")) {
+ $order[$idx] = "navigation";
+ } elseif ($value == $lng->txt("blog_keywords")) {
+ $order[$idx] = "keywords";
+ } else {
+ $order[$idx]= "authors";
+ }
+ }
+ $this->object->setOrder($order);
+ // banner field is optional
+ $banner = $a_form->getItemByPostVar("banner");
+ if ($banner) {
+ if ($_FILES["banner"]["tmp_name"]) {
+ $this->object->uploadImage($_FILES["banner"]);
+ } elseif ($banner->getDeletionFlag()) {
+ $this->object->deleteImage();
+ }
+ }
+ }
+
+ public function setTabs()
+ {
+ $lng = $this->lng;
+ $ilHelp = $this->help;
+
+ if ($this->id_type == self::WORKSPACE_NODE_ID) {
+ $this->ctrl->setParameter($this, "wsp_id", $this->node_id);
+ }
+
+ $ilHelp->setScreenIdComponent("blog");
+
+ if ($this->checkPermissionBool("read")) {
+ $this->tabs_gui->addTab(
+ "content",
+ $lng->txt("content"),
+ $this->ctrl->getLinkTarget($this, "")
+ );
+ }
+ if ($this->checkPermissionBool("read") && !$this->prtf_embed) {
+ $this->tabs_gui->addTab(
+ "id_info",
+ $lng->txt("info_short"),
+ $this->ctrl->getLinkTargetByClass(array("ilobjbloggui", "ilinfoscreengui"), "showSummary")
+ );
+ }
+
+ if ($this->checkPermissionBool("write")) {
+ $this->tabs_gui->addTab(
+ "settings",
+ $lng->txt("settings"),
+ $this->ctrl->getLinkTarget($this, "edit")
+ );
+
+ if (!$this->prtf_embed) {
+ if ($this->id_type == self::REPOSITORY_NODE_ID) {
+ $this->tabs_gui->addTab(
+ "contributors",
+ $lng->txt("blog_contributors"),
+ $this->ctrl->getLinkTarget($this, "contributors")
+ );
+ }
+
+ if ($this->id_type == self::REPOSITORY_NODE_ID) {
+ $this->tabs_gui->addTab(
+ "export",
+ $lng->txt("export"),
+ $this->ctrl->getLinkTargetByClass("ilexportgui", "")
+ );
+ }
+ }
+ }
+
+ if (!$this->prtf_embed) {
+ if ($this->mayContribute()) {
+ $this->tabs_gui->addNonTabbedLink(
+ "preview",
+ $lng->txt("blog_preview"),
+ $this->ctrl->getLinkTarget($this, "preview")
+ );
+ }
+ parent::setTabs();
+ }
+ }
+
+ public function executeCommand()
+ {
+ $ilCtrl = $this->ctrl;
+ $tpl = $this->tpl;
+ $ilTabs = $this->tabs;
+ $lng = $this->lng;
+ $ilNavigationHistory = $this->nav_history;
+
+ // goto link to blog posting
+ if ($this->gtp > 0) {
+ $page_id = $this->gtp;
+ include_once "Modules/Blog/classes/class.ilBlogPosting.php";
+ if (ilBlogPosting::exists($this->object_id, $page_id)) {
+ // #12312
+ $ilCtrl->setCmdClass("ilblogpostinggui");
+ $ilCtrl->setParameterByClass("ilblogpostinggui", "blpg", $page_id);
+ $ilCtrl->redirectByClass("ilblogpostinggui", "previewFullscreen");
+ } else {
+ ilUtil::sendFailure($lng->txt("blog_posting_not_found"));
+ }
+ }
+
+ $next_class = $ilCtrl->getNextClass($this);
+ $cmd = $ilCtrl->getCmd();
+
+ if ($this->id_type == self::REPOSITORY_NODE_ID) {
+ // add entry to navigation history
+ if (!$this->getCreationMode() &&
+ $this->getAccessHandler()->checkAccess("read", "", $this->node_id)) {
+ // see #22067
+ $link = $ilCtrl->getLinkTargetByClass(["ilrepositorygui", "ilObjBlogGUI"], "preview");
+ $ilNavigationHistory->addItem($this->node_id, $link, "blog");
+ }
+ }
+
+ switch ($next_class) {
+ case 'ilblogpostinggui':
+ if (!$this->prtf_embed) {
+ $tpl->getStandardTemplate();
+ }
+
+ if (!$this->checkPermissionBool("read") && !$this->prtf_embed) {
+ ilUtil::sendInfo($lng->txt("no_permission"));
+ return;
+ }
+
+ // #9680
+ if ($this->id_type == self::REPOSITORY_NODE_ID) {
+ $this->setLocator();
+ } else {
+ include_once "Services/Form/classes/class.ilFileInputGUI.php";
+ ilFileInputGUI::setPersonalWorkspaceQuotaCheck(true);
+ }
+ $ilTabs->setBackTarget(
+ $lng->txt("back"),
+ $ilCtrl->getLinkTarget($this, "")
+ );
+
+ $style_sheet_id = ilObjStyleSheet::getEffectiveContentStyleId(
+ $this->object->getStyleSheetId(),
+ "blog"
+ );
+
+ include_once("./Modules/Blog/classes/class.ilBlogPostingGUI.php");
+ $bpost_gui = new ilBlogPostingGUI(
+ $this->node_id,
+ $this->getAccessHandler(),
+ $this->blpg,
+ $this->old_nr,
+ ($this->object->getNotesStatus() && !$this->disable_notes),
+ $this->mayEditPosting($this->blpg),
+ $style_sheet_id
+ );
+
+ // keep preview mode through notes gui (has its own commands)
+ switch ($cmd) {
+ // blog preview
+ case "previewFullscreen":
+ $ilCtrl->setParameter($this, "prvm", "fsc");
+ break;
+
+ // blog in portfolio
+ case "previewEmbedded":
+ $ilCtrl->setParameter($this, "prvm", "emb");
+ break;
+
+ // edit
+ default:
+ $this->setContentStyleSheet();
+
+
+ if (!$this->prtf_embed) {
+ $this->ctrl->setParameterByClass("ilblogpostinggui", "blpg", $this->blpg);
+ $this->tabs_gui->addNonTabbedLink(
+ "preview",
+ $lng->txt("blog_preview"),
+ $this->ctrl->getLinkTargetByClass("ilblogpostinggui", "previewFullscreen")
+ );
+ $this->ctrl->setParameterByClass("ilblogpostinggui", "blpg", "");
+ } else {
+ $this->ctrl->setParameterByClass("ilobjportfoliogui", "user_page", $this->ppage);
+ $this->tabs_gui->addNonTabbedLink(
+ "preview",
+ $lng->txt("blog_preview"),
+ $this->ctrl->getLinkTargetByClass("ilobjportfoliogui", "preview")
+ );
+ $this->ctrl->setParameterByClass("ilobjportfoliogui", "user_page", "");
+ }
+ break;
+ }
+
+ // keep preview mode through notes gui
+ if ($this->prvm) {
+ $cmd = "preview" . (($this->prvm == "fsc") ? "Fullscreen" : "Embedded");
+ }
+ if (in_array($cmd, array("previewFullscreen", "previewEmbedded"))) {
+ $this->renderToolbarNavigation($this->items, true);
+ }
+ $ret = $ilCtrl->forwardCommand($bpost_gui);
+ if ($ret != "") {
+
+ // $is_owner = $this->object->getOwner() == $ilUser->getId();
+ $is_owner = $this->mayContribute();
+ $is_active = $bpost_gui->getBlogPosting()->getActive();
+
+ // do not show inactive postings
+ if (($cmd == "previewFullscreen" || $cmd == "previewEmbedded")
+ && !$is_owner && !$is_active) {
+ $this->ctrl->redirect($this, "preview");
+ }
+
+ switch ($cmd) {
+ // blog preview
+ case "previewFullscreen":
+ $this->addHeaderActionForCommand($cmd);
+ $this->filterInactivePostings();
+ $nav = $this->renderNavigation($this->items, "preview", $cmd);
+ $this->renderFullScreen($ret, $nav);
+ break;
+
+ // blog in portfolio
+ case "previewEmbedded":
+ $this->filterInactivePostings();
+ $nav = $this->renderNavigation($this->items, "gethtml", $cmd);
+ return $this->buildEmbedded($ret, $nav);
+
+ // ilias/editor
+ default:
+ // infos about draft status / snippet
+ $info = array();
+ if (!$is_active) {
+ // single author blog (owner) in personal workspace
+ if ($this->id_type == self::WORKSPACE_NODE_ID) {
+ $info[] = $lng->txt("blog_draft_info");
+ } else {
+ $info[] = $lng->txt("blog_draft_info_contributors");
+ }
+ }
+ if ($cmd != "history" && $is_active && empty($info)) {
+ $info[] = $lng->txt("blog_new_posting_info");
+ $public_action = true;
+ }
+ if ($this->object->hasApproval() && !$bpost_gui->getBlogPosting()->isApproved()) {
+ // #9737
+ $info[] = $lng->txt("blog_posting_edit_approval_info");
+ }
+ if (sizeof($info) && !$tpl->hasMessage("info")) { // #15121
+ if ($public_action) {
+ ilUtil::sendSuccess(implode("
", $info));
+ } else {
+ ilUtil::sendInfo(implode("
", $info));
+ }
+ }
+ // revert to edit cmd to avoid confusion
+ $this->addHeaderActionForCommand("render");
+ $tpl->setContent($ret);
+ $nav = $this->renderNavigation($this->items, "render", $cmd, null, $is_owner);
+ $tpl->setRightContent($nav);
+ break;
+ }
+ }
+ break;
+
+ case "ilinfoscreengui":
+ $this->prepareOutput();
+ $this->addHeaderActionForCommand("render");
+ $this->infoScreenForward();
+ break;
+
+ case "ilnotegui":
+ $this->preview();
+ break;
+
+ case "ilcommonactiondispatchergui":
+ include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php");
+ $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall();
+ $this->ctrl->forwardCommand($gui);
+ break;
+
+ case "ilpermissiongui":
+ $this->prepareOutput();
+ $ilTabs->activateTab("id_permissions");
+ include_once("Services/AccessControl/classes/class.ilPermissionGUI.php");
+ $perm_gui = new ilPermissionGUI($this);
+ $this->ctrl->forwardCommand($perm_gui);
+ break;
+
+ case "ilobjectcopygui":
+ $this->prepareOutput();
+ include_once "./Services/Object/classes/class.ilObjectCopyGUI.php";
+ $cp = new ilObjectCopyGUI($this);
+ $cp->setType("blog");
+ $this->ctrl->forwardCommand($cp);
+ break;
+
+ case 'ilrepositorysearchgui':
+ $this->prepareOutput();
+ $ilTabs->activateTab("contributors");
+ include_once('./Services/Search/classes/class.ilRepositorySearchGUI.php');
+ $rep_search = new ilRepositorySearchGUI();
+ $rep_search->setTitle($this->lng->txt("blog_add_contributor"));
+ $rep_search->setCallback($this, 'addContributor', $this->object->getAllLocalRoles($this->node_id));
+ $this->ctrl->setReturn($this, 'contributors');
+ $ret =&$this->ctrl->forwardCommand($rep_search);
+ break;
+
+ case 'ilexportgui':
+ $this->prepareOutput();
+ $ilTabs->activateTab("export");
+ include_once("./Services/Export/classes/class.ilExportGUI.php");
+ $exp_gui = new ilExportGUI($this);
+ $exp_gui->addFormat("xml");
+ $exp_gui->addFormat("html", null, $this, "buildExportFile"); // #13419
+ $ret = $ilCtrl->forwardCommand($exp_gui);
+ break;
+
+ case "ilobjstylesheetgui":
+ include_once("./Services/Style/Content/classes/class.ilObjStyleSheetGUI.php");
+ $this->ctrl->setReturn($this, "editStyleProperties");
+ $style_gui = new ilObjStyleSheetGUI("", $this->object->getStyleSheetId(), false, false);
+ $style_gui->omitLocator();
+ if ($cmd == "create" || $this->new_type == "sty") {
+ $style_gui->setCreationMode(true);
+ }
+
+ if ($cmd == "confirmedDelete") {
+ $this->object->setStyleSheetId(0);
+ $this->object->update();
+ }
+
+ $ret = $this->ctrl->forwardCommand($style_gui);
+
+ if ($cmd == "save" || $cmd == "copyStyle" || $cmd == "importStyle") {
+ $style_id = $ret;
+ $this->object->setStyleSheetId($style_id);
+ $this->object->update();
+ $this->ctrl->redirectByClass("ilobjstylesheetgui", "edit");
+ }
+ break;
+
+ case "ilblogexercisegui":
+ $this->ctrl->setReturn($this, "render");
+ include_once "Modules/Blog/classes/class.ilBlogExerciseGUI.php";
+ $gui = new ilBlogExerciseGUI($this->node_id);
+ $this->ctrl->forwardCommand($gui);
+ break;
+
+ case 'ilobjnotificationsettingsgui':
+ $this->prepareOutput();
+ $ilTabs->activateTab("settings");
+ $this->setSettingsSubTabs("notifications");
+ include_once("./Services/Notification/classes/class.ilObjNotificationSettingsGUI.php");
+ $gui = new ilObjNotificationSettingsGUI($this->object->getRefId());
+ $this->ctrl->forwardCommand($gui);
+ break;
+
+ default:
+ if ($cmd != "gethtml") {
+ // desktop item handling, must be toggled before header action
+ if ($cmd == "addToDesk" || $cmd == "removeFromDesk") {
+ $this->{$cmd . "Object"}();
+ if ($this->prvm) {
+ $cmd = "preview";
+ } else {
+ $cmd = "render";
+ }
+ $ilCtrl->setCmd($cmd);
+ }
+ $this->addHeaderActionForCommand($cmd);
+ }
+ if (!$this->prtf_embed) {
+ return parent::executeCommand();
+ } else {
+ $this->setTabs();
+
+ if (!$cmd) {
+ $cmd = "render";
+ }
+ return $this->$cmd();
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * this one is called from the info button in the repository
+ * not very nice to set cmdClass/Cmd manually, if everything
+ * works through ilCtrl in the future this may be changed
+ */
+ public function infoScreen()
+ {
+ $this->ctrl->setCmd("showSummary");
+ $this->ctrl->setCmdClass("ilinfoscreengui");
+ $this->infoScreenForward();
+ }
+
+ /**
+ * show information screen
+ */
+ public function infoScreenForward()
+ {
+ $ilTabs = $this->tabs;
+
+ $ilTabs->activateTab("id_info");
+
+ $this->checkPermission("visible");
+
+ include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php");
+ $info = new ilInfoScreenGUI($this);
+
+ if ($this->id_type != self::WORKSPACE_NODE_ID) {
+ $info->enablePrivateNotes();
+ }
+
+ if ($this->checkPermissionBool("read")) {
+ $info->enableNews();
+ }
+
+ // no news editing for files, just notifications
+ $info->enableNewsEditing(false);
+ if ($this->checkPermissionBool("write")) {
+ $news_set = new ilSetting("news");
+ $enable_internal_rss = $news_set->get("enable_rss_for_internal");
+
+ if ($enable_internal_rss) {
+ $info->setBlockProperty("news", "settings", true);
+ $info->setBlockProperty("news", "public_notifications_option", true);
+ }
+ }
+
+ // standard meta data
+ $info->addMetaDataSections($this->object->getId(), 0, $this->object->getType());
+
+ if ($this->id_type == self::WORKSPACE_NODE_ID) {
+ $info->addProperty($this->lng->txt("perma_link"), $this->getPermanentLinkWidget());
+ }
+
+ $this->ctrl->forwardCommand($info);
+ }
+
+ /**
+ * Create new posting
+ */
+ public function createPosting()
+ {
+ $ilCtrl = $this->ctrl;
+ $ilUser = $this->user;
+
+ $title = trim(ilUtil::stripSlashes($_POST["title"]));
+ if ($title) {
+ // create new posting
+ include_once("./Modules/Blog/classes/class.ilBlogPosting.php");
+ $posting = new ilBlogPosting();
+ $posting->setTitle($title);
+ $posting->setBlogId($this->object->getId());
+ $posting->setActive(false);
+ $posting->setAuthor($ilUser->getId());
+ $posting->create();
+
+ // switch month list to current month (will include new posting)
+ $ilCtrl->setParameter($this, "bmn", date("Y-m"));
+
+ $ilCtrl->setParameterByClass("ilblogpostinggui", "blpg", $posting->getId());
+ $ilCtrl->redirectByClass("ilblogpostinggui", "edit");
+ } else {
+ ilUtil::sendFailure($this->lng->txt("msg_no_title"), true);
+ $ilCtrl->redirect($this, "render");
+ }
+ }
+
+ // --- ObjectGUI End
+
+
+ /**
+ * Render object context
+ */
+ public function render()
+ {
+ $tpl = $this->tpl;
+ $ilTabs = $this->tabs;
+ $ilCtrl = $this->ctrl;
+ $lng = $this->lng;
+ $ilToolbar = new ilToolbarGUI();
+ $ilUser = $this->user;
+ $tree = $this->tree;
+
+ if (!$this->checkPermissionBool("read")) {
+ ilUtil::sendInfo($lng->txt("no_permission"));
+ return;
+ }
+
+ $ilTabs->activateTab("content");
+
+ // toolbar
+ if ($this->mayContribute()) {
+ $ilToolbar->setFormAction($ilCtrl->getFormAction($this, "createPosting"));
+
+ include_once "Services/Form/classes/class.ilPropertyFormGUI.php";
+ $title = new ilTextInputGUI($lng->txt("title"), "title");
+ $ilToolbar->addStickyItem($title, $lng->txt("title"));
+
+ include_once "Services/UIComponent/Button/classes/class.ilSubmitButton.php";
+ $button = ilSubmitButton::getInstance();
+ $button->setCaption("blog_add_posting");
+ $button->setCommand("createPosting");
+ $ilToolbar->addStickyItem($button);
+
+ // #18763
+ $first = array_shift((array_keys($this->items)));
+ if ($first != $this->month) {
+ $ilToolbar->addSeparator();
+
+ $ilCtrl->setParameter($this, "bmn", $first);
+ $url = $ilCtrl->getLinkTarget($this, "");
+ $ilCtrl->setParameter($this, "bmn", $this->month);
+
+ include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php";
+ $button = ilLinkButton::getInstance();
+ $button->setCaption("blog_show_latest");
+ $button->setUrl($url);
+ $ilToolbar->addButtonInstance($button);
+ }
+
+ // exercise blog?
+ include_once "Modules/Blog/classes/class.ilBlogExerciseGUI.php";
+ $message = ilBlogExerciseGUI::checkExercise($this->node_id);
+ }
+
+ // $is_owner = ($this->object->getOwner() == $ilUser->getId());
+ $is_owner = $this->mayContribute();
+
+ $list_items = $this->getListItems($is_owner);
+
+ $list = $nav = "";
+ if ($list_items) {
+ $list = $this->renderList($list_items, "preview", null, $is_owner);
+ $nav = $this->renderNavigation($this->items, "render", "preview", null, $is_owner);
+ }
+
+ $this->setContentStyleSheet();
+
+ $tpl->setContent($message . $ilToolbar->getHTML() . $list);
+ $tpl->setRightContent($nav);
+ }
+
+ /**
+ * Return embeddable HTML chunk
+ *
+ * @return string
+ */
+ public function getHTML()
+ {
+ $ilUser = $this->user;
+ $ilCtrl = $this->ctrl;
+ $lng = $this->lng;
+
+ // getHTML() is called by ilRepositoryGUI::show()
+ if ($this->id_type == self::REPOSITORY_NODE_ID) {
+ return;
+ }
+
+ // there is no way to do a permissions check here, we have no wsp
+
+ $this->filterInactivePostings();
+
+ $list_items = $this->getListItems();
+
+ $list = $nav = "";
+ if ($list_items) {
+ $list = $this->renderList($list_items, "previewEmbedded");
+ $nav = $this->renderNavigation($this->items, "gethtml", "previewEmbedded");
+ }
+ // quick editing in portfolio
+ elseif ($this->prt_id) {
+ // see renderList()
+ if (ilObject::_lookupOwner($this->prt_id) == $ilUser->getId()) {
+ // see ilPortfolioPageTableGUI::fillRow()
+ $ilCtrl->setParameterByClass("ilportfoliopagegui", "ppage", $this->user_page);
+ $link = $ilCtrl->getLinkTargetByClass(array("ilportfoliopagegui", "ilobjbloggui"), "render");
+ $ilCtrl->setParameterByClass("ilportfoliopagegui", "ppage", "");
+
+ include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php";
+ $btn = ilLinkButton::getInstance();
+ $btn->setCaption(sprintf($lng->txt("prtf_edit_embedded_blog"), $this->object->getTitle()), false);
+ $btn->setUrl($link);
+ $btn->setPrimary(true);
+
+ $list = $btn->render();
+ }
+ }
+
+ return $this->buildEmbedded($list, $nav);
+ }
+
+ /**
+ * Filter blog postings by month, keyword or author
+ *
+ * @param bool $a_show_inactive
+ * @return array
+ */
+ protected function getListItems($a_show_inactive = false)
+ {
+ if ($this->author) {
+ $list_items = array();
+ foreach ($this->items as $month => $items) {
+ foreach ($items as $id => $item) {
+ if ($item["author"] == $this->author ||
+ (is_array($item["editors"]) && in_array($this->author, $item["editors"]))) {
+ $list_items[$id] = $item;
+ }
+ }
+ }
+ } elseif ($this->keyword) {
+ $list_items = $this->filterItemsByKeyword($this->items, $this->keyword);
+ } else {
+ $max = $this->object->getOverviewPostings();
+ if ($this->month_default && $max) {
+ $list_items = array();
+ foreach ($this->items as $month => $postings) {
+ foreach ($postings as $id => $item) {
+ if (!$a_show_inactive &&
+ !ilBlogPosting::_lookupActive($id, "blp")) {
+ continue;
+ }
+ $list_items[$id] = $item;
+
+ if (sizeof($list_items) >= $max) {
+ break(2);
+ }
+ }
+ }
+ } else {
+ $list_items = $this->items[$this->month];
+ }
+ }
+ return $list_items;
+ }
+
+ /**
+ * Render fullscreen presentation
+ */
+ public function preview()
+ {
+ global $DIC;
+
+ $lng = $DIC->language();
+ $toolbar = $DIC->toolbar();
+
+ if (!$this->checkPermissionBool("read")) {
+ ilUtil::sendInfo($lng->txt("no_permission"));
+ return;
+ }
+
+ $this->filterInactivePostings();
+
+ $list_items = $this->getListItems();
+
+ $list = $nav = "";
+ if ($list_items) {
+ $list = $this->renderList($list_items, "previewFullscreen");
+ $nav = $this->renderNavigation($this->items, "preview", "previewFullscreen");
+ $this->renderToolbarNavigation($this->items);
+ $list.= $toolbar->getHTML();
+ }
+
+ $this->renderFullScreen($list, $nav);
+ }
+
+ /**
+ * Build and deliver export file
+ */
+ public function export()
+ {
+ $zip = $this->buildExportFile();
+
+ ilUtil::deliverFile($zip, $this->object->getTitle() . ".zip", '', false, true);
+ }
+
+
+ // --- helper functions
+
+ /**
+ * Combine content (list/posting) and navigation to html chunk
+ *
+ * @param string $a_content
+ * @param string $a_nav
+ * @return string
+ */
+ protected function buildEmbedded($a_content, $a_nav)
+ {
+ $wtpl = new ilTemplate("tpl.blog_embedded.html", true, true, "Modules/Blog");
+ $wtpl->setVariable("VAL_LIST", $a_content);
+ $wtpl->setVariable("VAL_NAVIGATION", $a_nav);
+ return $wtpl->get();
+ }
+
+ /**
+ * Build fullscreen context
+ *
+ * @param string $a_content
+ * @param string $a_navigation
+ */
+ public function renderFullScreen($a_content, $a_navigation)
+ {
+ $tpl = $this->tpl;
+ $ilUser = $this->user;
+ $ilTabs = $this->tabs;
+ $ilLocator = $this->locator;
+
+ $owner = $this->object->getOwner();
+
+ $ilTabs->clearTargets();
+ $ilLocator->clearItems();
+ $tpl->setLocator();
+
+ $back_caption = "";
+
+ // back (edit)
+ if ($owner == $ilUser->getId()) {
+ // from shared/deeplink
+ if ($this->id_type == self::WORKSPACE_NODE_ID) {
+ $back = "ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToWorkspace&wsp_id=" . $this->node_id;
+ }
+ // from editor (#10073)
+ elseif ($this->mayContribute()) {
+ $this->ctrl->setParameter($this, "prvm", "");
+ if ($this->blpg == 0) {
+ $back = $this->ctrl->getLinkTarget($this, "");
+ } else {
+ $this->ctrl->setParameterByClass("ilblogpostinggui", "bmn", $this->month);
+ $this->ctrl->setParameterByClass("ilblogpostinggui", "blpg", $this->blpg);
+ $back = $this->ctrl->getLinkTargetByClass("ilblogpostinggui", "preview");
+ }
+ $this->ctrl->setParameter($this, "prvm", $this->prvm);
+ }
+
+ $back_caption = $this->lng->txt("blog_back_to_blog_owner");
+ }
+ // back
+ elseif ($ilUser->getId() && $ilUser->getId() != ANONYMOUS_USER_ID) {
+ // workspace (always shared)
+ if ($this->id_type == self::WORKSPACE_NODE_ID) {
+ $back = "ilias.php?baseClass=ilPersonalDesktopGUI&cmd=jumpToWorkspace&dsh=" . $owner;
+ }
+ // contributor
+ elseif ($this->mayContribute()) {
+ $back = $this->ctrl->getLinkTarget($this, "");
+ $back_caption = $this->lng->txt("blog_back_to_blog_owner");
+ }
+ // listgui / parent container
+ else {
+ $tree = $this->tree;
+ $parent_id = $tree->getParentId($this->node_id);
+ include_once "Services/Link/classes/class.ilLink.php";
+ $back = ilLink::_getStaticLink($parent_id);
+ }
+ }
+
+ $ilMainMenu = $this->main_menu;
+ $ilMainMenu->setMode(ilMainMenuGUI::MODE_TOPBAR_ONLY);
+ $ilMainMenu->setTopBarBack($back, $back_caption);
+
+ $this->renderFullscreenHeader($tpl, $owner);
+
+ // #13564
+ $this->ctrl->setParameter($this, "bmn", "");
+ $tpl->setTitleUrl($this->ctrl->getLinkTarget($this, "preview"));
+ $this->ctrl->setParameter($this, "bmn", $this->month);
+
+ $this->setContentStyleSheet();
+
+ // content
+ $tpl->setContent($a_content);
+ $tpl->setRightContent($a_navigation);
+ }
+
+ /**
+ * Render banner, user name
+ *
+ * @param object $a_tpl
+ * @param int $a_user_id
+ * @param bool $a_export_path
+ */
+ protected function renderFullscreenHeader($a_tpl, $a_user_id, $a_export = false)
+ {
+ $ilUser = $this->user;
+
+ if (!$a_export) {
+ require_once('Services/Tracking/classes/class.ilChangeEvent.php');
+ ilChangeEvent::_recordReadEvent(
+ $this->object->getType(),
+ $this->node_id,
+ $this->object->getId(),
+ $ilUser->getId()
+ );
+ }
+
+ // repository blogs are multi-author
+ $name = null;
+ if ($this->id_type != self::REPOSITORY_NODE_ID) {
+ $name = ilObjUser::_lookupName($a_user_id);
+ $name = $name["lastname"] . ", " . ($t = $name["title"] ? $t . " " : "") . $name["firstname"];
+ }
+
+ // show banner?
+ $banner = false;
+ $blga_set = new ilSetting("blga");
+ if ($blga_set->get("banner")) {
+ require_once('./Services/WebAccessChecker/classes/class.ilWACSignedPath.php');
+ $banner = ilWACSignedPath::signFile($this->object->getImageFullPath());
+ $banner_width = $blga_set->get("banner_width");
+ $banner_height = $blga_set->get("banner_height");
+ if ($a_export) {
+ $banner = basename($banner);
+ }
+ }
+
+ $ppic = null;
+ if ($this->object->hasProfilePicture()) {
+ // repository (multi-user)
+ if ($this->id_type == self::REPOSITORY_NODE_ID) {
+ // #15030
+ if ($this->blpg > 0 && !$a_export) {
+ include_once "Modules/Blog/classes/class.ilBlogPosting.php";
+ $post = new ilBlogPosting($this->blpg);
+ $author_id = $post->getAuthor();
+ if ($author_id) {
+ $ppic = ilObjUser::_getPersonalPicturePath($author_id, "xsmall", true, true);
+
+ $name = ilObjUser::_lookupName($author_id);
+ $name = $name["lastname"] . ", " . ($t = $name["title"] ? $t . " " : "") . $name["firstname"];
+ }
+ }
+ }
+ // workspace (author == owner)
+ else {
+ $ppic = ilObjUser::_getPersonalPicturePath($a_user_id, "xsmall", true, true);
+ if ($a_export) {
+ $ppic = basename($ppic);
+ }
+ }
+ }
+
+ $a_tpl->resetHeaderBlock(false);
+ // $a_tpl->setBackgroundColor($this->object->getBackgroundColor());
+ $a_tpl->setBanner($banner, $banner_width, $banner_height, $a_export);
+ $a_tpl->setTitleIcon($ppic);
+ $a_tpl->setTitle($this->object->getTitle());
+ // $a_tpl->setTitleColor($this->object->getFontColor());
+ $a_tpl->setDescription($name);
+
+ // to get rid of locator in repository preview
+ $a_tpl->setVariable("LOCATOR", "");
+
+ // :TODO: obsolete?
+ // $a_tpl->setBodyClass("std ilExternal ilBlog");
+ }
+
+ /**
+ * Gather all blog postings
+ *
+ * @param int $a_obj_id
+ * @return array
+ */
+ protected function buildPostingList($a_obj_id)
+ {
+ $author_found = false;
+
+ $items = array();
+ foreach (ilBlogPosting::getAllPostings($a_obj_id) as $posting) {
+ if ($this->author &&
+ ($posting["author"] == $this->author ||
+ (is_array($posting["editors"]) && in_array($this->author, $posting["editors"])))) {
+ $author_found = true;
+ }
+
+ $month = substr($posting["created"]->get(IL_CAL_DATE), 0, 7);
+ $items[$month][$posting["id"]] = $posting;
+ }
+
+ if ($this->author && !$author_found) {
+ $this->author = null;
+ }
+
+ return $items;
+ }
+
+ /**
+ * Build posting month list
+ *
+ * @param array $items
+ * @param string $a_cmd
+ * @param bool $a_link_template
+ * @param bool $a_show_inactive
+ * @param string $a_export_directory
+ * @return string
+ */
+ public function renderList(array $items, $a_cmd = "preview", $a_link_template = null, $a_show_inactive = false, $a_export_directory = null)
+ {
+ $lng = $this->lng;
+ $ilCtrl = $this->ctrl;
+ $ilUser = $this->user;
+
+ include_once "Services/Calendar/classes/class.ilCalendarUtil.php";
+ $wtpl = new ilTemplate("tpl.blog_list.html", true, true, "Modules/Blog");
+
+ // quick editing in portfolio
+ if ($this->prt_id > 0 &&
+ stristr($a_cmd, "embedded")) {
+ if (ilObject::_lookupOwner($this->prt_id) == $ilUser->getId()) {
+ // see ilPortfolioPageTableGUI::fillRow()
+ $ilCtrl->setParameterByClass("ilportfoliopagegui", "ppage", $this->user_page);
+ $link = $ilCtrl->getLinkTargetByClass(array("ilportfoliopagegui", "ilobjbloggui"), "render");
+ $ilCtrl->setParameterByClass("ilportfoliopagegui", "ppage", "");
+
+ include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php";
+ $list = new ilAdvancedSelectionListGUI();
+ $list->setListTitle($lng->txt("action"));
+ $list->addItem(
+ sprintf($lng->txt("prtf_edit_embedded_blog"), $this->object->getTitle()),
+ "",
+ $link
+ );
+
+ /*
+ include_once "Services/UIComponent/Button/classes/class.ilLinkButton.php";
+ $btn = ilLinkButton::getInstance();
+ $btn->setCaption(sprintf($lng->txt("prtf_edit_embedded_blog"), $this->object->getTitle()), false);
+ $btn->setUrl($link);
+ */
+
+ $wtpl->setCurrentBlock("prtf_edit_bl");
+ $wtpl->setVariable("PRTF_BLOG_EDIT", $list->getHTML());
+ $wtpl->parseCurrentBlock();
+ }
+ }
+
+ $is_admin = $this->isAdmin();
+
+ include_once("./Modules/Blog/classes/class.ilBlogPostingGUI.php");
+ $last_month = null;
+ $is_empty = true;
+ foreach ($items as $item) {
+ // only published items
+ $is_active = ilBlogPosting::_lookupActive($item["id"], "blp");
+ if (!$is_active && !$a_show_inactive) {
+ continue;
+ }
+
+ $is_empty = false;
+
+ if (!$this->keyword && !$this->author) {
+ $month = substr($item["created"]->get(IL_CAL_DATE), 0, 7);
+ }
+
+ if (!$last_month || $last_month != $month) {
+ if ($last_month) {
+ $wtpl->setCurrentBlock("month_bl");
+ $wtpl->parseCurrentBlock();
+ }
+
+ // title according to current "filter"/navigation
+ if ($this->keyword) {
+ $title = $lng->txt("blog_keyword") . ": " . $this->keyword;
+ } elseif ($this->author) {
+ include_once "Services/User/classes/class.ilUserUtil.php";
+ $title = $lng->txt("blog_author") . ": " . ilUserUtil::getNamePresentation($this->author);
+ } else {
+ include_once "Services/Calendar/classes/class.ilCalendarUtil.php";
+ $title = ilCalendarUtil::_numericMonthToString((int) substr($month, 5)) .
+ " " . substr($month, 0, 4);
+
+ $last_month = $month;
+ }
+
+ $wtpl->setVariable("TXT_CURRENT_MONTH", $title);
+ }
+
+ if (!$a_link_template) {
+ $ilCtrl->setParameterByClass("ilblogpostinggui", "bmn", $this->month);
+ $ilCtrl->setParameterByClass("ilblogpostinggui", "blpg", $item["id"]);
+ $preview = $ilCtrl->getLinkTargetByClass("ilblogpostinggui", $a_cmd);
+ } else {
+ $preview = $this->buildExportLink($a_link_template, "posting", $item["id"]);
+ }
+
+ // actions
+ $posting_edit = $this->mayEditPosting($item["id"], $item["author"]);
+ if (($posting_edit || $is_admin) && !$a_link_template && $a_cmd == "preview") {
+ include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php");
+ $alist = new ilAdvancedSelectionListGUI();
+ $alist->setId($item["id"]);
+ $alist->setListTitle($lng->txt("actions"));
+
+ if ($is_active && $this->object->hasApproval() && !$item["approved"]) {
+ if ($is_admin) {
+ $ilCtrl->setParameter($this, "apid", $item["id"]);
+ $alist->addItem(
+ $lng->txt("blog_approve"),
+ "approve",
+ $ilCtrl->getLinkTarget($this, "approve")
+ );
+ $ilCtrl->setParameter($this, "apid", "");
+ }
+
+ $wtpl->setVariable("APPROVAL", $lng->txt("blog_needs_approval"));
+ }
+
+ if ($posting_edit) {
+ $alist->addItem(
+ $lng->txt("edit_content"),
+ "edit",
+ $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "edit")
+ );
+
+ // #11858
+ if ($is_active) {
+ $alist->addItem(
+ $lng->txt("blog_toggle_draft"),
+ "deactivate",
+ $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "deactivatePageToList")
+ );
+ } else {
+ $alist->addItem(
+ $lng->txt("blog_toggle_final"),
+ "activate",
+ $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "activatePageToList")
+ );
+ }
+
+ $alist->addItem(
+ $lng->txt("rename"),
+ "rename",
+ $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "edittitle")
+ );
+
+ if ($this->object->hasKeywords()) { // #13616
+ $alist->addItem(
+ $lng->txt("blog_edit_keywords"),
+ "keywords",
+ $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "editKeywords")
+ );
+ }
+
+ $alist->addItem(
+ $lng->txt("blog_edit_date"),
+ "editdate",
+ $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "editdate")
+ );
+ $alist->addItem(
+ $lng->txt("delete"),
+ "delete",
+ $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "deleteBlogPostingConfirmationScreen")
+ );
+ } elseif ($is_admin) {
+ // #10513
+ if ($is_active) {
+ $ilCtrl->setParameter($this, "apid", $item["id"]);
+ $alist->addItem(
+ $lng->txt("blog_toggle_draft_admin"),
+ "deactivate",
+ $ilCtrl->getLinkTarget($this, "deactivateAdmin")
+ );
+ $ilCtrl->setParameter($this, "apid", "");
+ }
+
+ $alist->addItem(
+ $lng->txt("delete"),
+ "delete",
+ $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "deleteBlogPostingConfirmationScreen")
+ );
+ }
+
+ $wtpl->setCurrentBlock("actions");
+ $wtpl->setVariable("ACTION_SELECTOR", $alist->getHTML());
+ $wtpl->parseCurrentBlock();
+ }
+
+ // comments
+ if ($this->object->getNotesStatus() && !$a_link_template && !$this->disable_notes) {
+ // count (public) notes
+ include_once("Services/Notes/classes/class.ilNote.php");
+ $count = sizeof(ilNote::_getNotesOfObject(
+ $this->obj_id,
+ $item["id"],
+ "blp",
+ IL_NOTE_PUBLIC
+ ));
+
+ if ($a_cmd != "preview") {
+ $wtpl->setCurrentBlock("comments");
+ $wtpl->setVariable("TEXT_COMMENTS", $lng->txt("blog_comments"));
+ $wtpl->setVariable("URL_COMMENTS", $preview);
+ $wtpl->setVariable("COUNT_COMMENTS", $count);
+ $wtpl->parseCurrentBlock();
+ }
+ /* we disabled comments in edit mode (should always be done via pagegui)
+ else
+ {
+ $hash = ilCommonActionDispatcherGUI::buildAjaxHash(ilCommonActionDispatcherGUI::TYPE_WORKSPACE,
+ $this->node_id, "blog", $this->obj_id, "blp", $item["id"]);
+ $notes_link = "#\" onclick=\"".ilNoteGUI::getListCommentsJSCall($hash);
+ }
+ */
+ }
+
+ // permanent link
+ if ($a_cmd != "preview" && $a_cmd != "previewEmbedded") {
+ if ($this->id_type == self::WORKSPACE_NODE_ID) {
+ $goto = $this->getAccessHandler()->getGotoLink($this->node_id, $this->obj_id, "_" . $item["id"]);
+ } else {
+ include_once "Services/Link/classes/class.ilLink.php";
+ $goto = ilLink::_getStaticLink($this->node_id, $this->getType(), true, "_" . $item["id"]);
+ }
+ $wtpl->setCurrentBlock("permalink");
+ $wtpl->setVariable("URL_PERMALINK", $goto);
+ $wtpl->setVariable("TEXT_PERMALINK", $lng->txt("blog_permanent_link"));
+ $wtpl->parseCurrentBlock();
+ }
+
+ $snippet = ilBlogPostingGUI::getSnippet(
+ $item["id"],
+ $this->object->hasAbstractShorten(),
+ $this->object->getAbstractShortenLength(),
+ "…",
+ $this->object->hasAbstractImage(),
+ $this->object->getAbstractImageWidth(),
+ $this->object->getAbstractImageHeight(),
+ $a_export_directory
+ );
+
+ if ($snippet) {
+ $wtpl->setCurrentBlock("more");
+ $wtpl->setVariable("URL_MORE", $preview);
+ $wtpl->setVariable("TEXT_MORE", $lng->txt("blog_list_more"));
+ $wtpl->parseCurrentBlock();
+ }
+
+
+
+ if (!$is_active) {
+ $wtpl->setCurrentBlock("draft_text");
+ $wtpl->setVariable("DRAFT_TEXT", $lng->txt("blog_draft_text"));
+ $wtpl->parseCurrentBlock();
+ $wtpl->setVariable("DRAFT_CLASS", " ilBlogListItemDraft");
+ }
+
+ $wtpl->setCurrentBlock("posting");
+
+ $author = "";
+ if ($this->id_type == self::REPOSITORY_NODE_ID) {
+ $authors = array();
+
+ $author_id = $item["author"];
+ if ($author_id) {
+ include_once "Services/User/classes/class.ilUserUtil.php";
+ $authors[] = ilUserUtil::getNamePresentation($author_id);
+ }
+
+ if (is_array($item["editors"])) {
+ foreach ($item["editors"] as $editor_id) {
+ $authors[] = ilUserUtil::getNamePresentation($editor_id);
+ }
+ }
+
+ if ($authors) {
+ $author = implode(", ", $authors) . " - ";
+ }
+ }
+
+ // title
+ $wtpl->setVariable("URL_TITLE", $preview);
+ $wtpl->setVariable("TITLE", $item["title"]);
$kw = ilBlogPosting::getKeywords($this->obj_id, $item["id"]);
natcasesort($kw);
$keywords = (count($kw) > 0)
- ? "
".$this->lng->txt("keywords").": ".implode(", ", $kw)
+ ? "
" . $this->lng->txt("keywords") . ": " . implode(", ", $kw)
: "";
- $wtpl->setVariable("DATETIME", $author.
- ilDatePresentation::formatDate($item["created"]).$keywords);
-
- // content
- $wtpl->setVariable("CONTENT", $snippet);
-
- $wtpl->parseCurrentBlock();
- }
-
- // permalink
- if($a_cmd == "previewFullscreen")
- {
- $this->tpl->setPermanentLink("blog", $this->node_id,
- ($this->id_type == self::WORKSPACE_NODE_ID)
- ? "_wsp"
- : "");
- }
-
- if(!$is_empty || $a_show_inactive)
- {
- return $wtpl->get();
- }
- }
-
- /**
- * Build navigation by date block
- *
- * @param array $a_items
- * @param string $a_list_cmd
- * @param string $a_posting_cmd
- * @param bool $a_link_template
- * @param bool $a_show_inactive
- * @return string
- */
- protected function renderNavigationByDate(array $a_items, $a_list_cmd = "render", $a_posting_cmd = "preview", $a_link_template = null, $a_show_inactive = false, $a_blpg = 0)
- {
- $ilCtrl = $this->ctrl;
-
- $blpg = ($a_blpg > 0)
- ? $a_blpg
- : $this->blpg;
-
-
- // gather page active status
- foreach($a_items as $month => $postings)
- {
- foreach(array_keys($postings) as $id)
- {
- $active = ilBlogPosting::_lookupActive($id, "blp");
- if(!$a_show_inactive && !$active)
- {
- unset($a_items[$month][$id]);
- }
- else
- {
- $a_items[$month][$id]["active"] = $active;
- }
- }
- if(!sizeof($a_items[$month]))
- {
- unset($a_items[$month]);
- }
- }
-
- // list month (incl. postings)
- if($this->object->getNavMode() == ilObjBlog::NAV_MODE_LIST || $a_link_template)
- {
- //$max_detail_postings = $this->object->getNavModeListPostings();
- $max_months = $this->object->getNavModeListMonths();
-
- $wtpl = new ilTemplate("tpl.blog_list_navigation_by_date.html", true, true, "Modules/Blog");
-
- $ilCtrl->setParameter($this, "blpg", "");
-
- include_once "Services/Calendar/classes/class.ilCalendarUtil.php";
- $counter = $mon_counter = $last_year = 0;
- foreach($a_items as $month => $postings)
- {
- if(!$a_link_template && $max_months && $mon_counter >= $max_months)
- {
- break;
- }
-
- $add_year = false;
- $year = substr($month, 0, 4);
- if(!$last_year || $year != $last_year)
- {
- // #13562
- $add_year = true;
- $last_year = $year;
- }
-
- $mon_counter++;
-
- $month_name = ilCalendarUtil::_numericMonthToString((int)substr($month, 5));
-
- if(!$a_link_template)
- {
- $ilCtrl->setParameter($this, "bmn", $month);
- $month_url = $ilCtrl->getLinkTarget($this, $a_list_cmd);
- }
- else
- {
- $month_url = $this->buildExportLink($a_link_template, "list", $month);
- }
-
- // list postings for month
- //if($counter < $max_detail_postings)
- if ($mon_counter <= $this->object->getNavModeListMonthsWithPostings())
- {
- if($add_year)
- {
- $wtpl->setCurrentBlock("navigation_year_details");
- $wtpl->setVariable("YEAR", $year);
- $wtpl->parseCurrentBlock();
- }
-
- foreach($postings as $id => $posting)
- {
- //if($max_detail_postings && $counter >= $max_detail_postings)
- //{
- // break;
- //}
-
- $counter++;
-
- $caption = /* ilDatePresentation::formatDate($posting["created"], IL_CAL_DATETIME).
- ", ".*/ $posting["title"];
-
- if(!$a_link_template)
- {
- $ilCtrl->setParameterByClass("ilblogpostinggui", "bmn", $month);
- $ilCtrl->setParameterByClass("ilblogpostinggui", "blpg", $id);
- $url = $ilCtrl->getLinkTargetByClass("ilblogpostinggui", $a_posting_cmd);
- }
- else
- {
- $url = $this->buildExportLink($a_link_template, "posting", $id);
- }
-
- if(!$posting["active"])
- {
- $wtpl->setVariable("NAV_ITEM_DRAFT", $this->lng->txt("blog_draft"));
- }
- else if($this->object->hasApproval() && !$posting["approved"])
- {
- $wtpl->setVariable("NAV_ITEM_APPROVAL", $this->lng->txt("blog_needs_approval"));
- }
-
- $wtpl->setCurrentBlock("navigation_item");
- $wtpl->setVariable("NAV_ITEM_URL", $url);
- $wtpl->setVariable("NAV_ITEM_CAPTION", $caption);
- $wtpl->parseCurrentBlock();
- }
-
- $wtpl->setCurrentBlock("navigation_month_details");
- $wtpl->setVariable("NAV_MONTH", $month_name);
- $wtpl->setVariable("URL_MONTH", $month_url);
- $wtpl->parseCurrentBlock();
- }
- // summarized month
- else
- {
- if($add_year)
- {
- $wtpl->setCurrentBlock("navigation_year");
- $wtpl->setVariable("YEAR", $year);
- $wtpl->parseCurrentBlock();
- }
-
- $wtpl->setCurrentBlock("navigation_month");
- $wtpl->setVariable("MONTH_NAME", $month_name);
- $wtpl->setVariable("URL_MONTH", $month_url);
- $wtpl->setVariable("MONTH_COUNT", sizeof($postings));
- $wtpl->parseCurrentBlock();
- }
- }
-
- $ilCtrl->setParameter($this, "bmn", $this->month);
- $ilCtrl->setParameterByClass("ilblogpostinggui", "bmn", "");
-
- return $wtpl->get();
- }
- // single month
- else
- {
- $wtpl = new ilTemplate("tpl.blog_list_navigation_month.html", true, true, "Modules/Blog");
-
- $ilCtrl->setParameter($this, "blpg", "");
-
- include_once "Services/Calendar/classes/class.ilCalendarUtil.php";
- $month_options = array();
- foreach($a_items as $month => $postings)
- {
- $month_name = ilCalendarUtil::_numericMonthToString((int)substr($month, 5)).
- " ".substr($month, 0, 4);
-
- $month_options[$month] = $month_name;
-
- if($month == $this->month)
- {
- if(!$a_link_template)
- {
- $ilCtrl->setParameter($this, "bmn", $month);
- $month_url = $ilCtrl->getLinkTarget($this, $a_list_cmd);
- }
- else
- {
- $month_url = $this->buildExportLink($a_link_template, "list", $month);
- }
-
- foreach($postings as $id => $posting)
- {
- $caption = /* ilDatePresentation::formatDate($posting["created"], IL_CAL_DATETIME).
- ", ".*/ $posting["title"];
-
- if(!$a_link_template)
- {
- $ilCtrl->setParameterByClass("ilblogpostinggui", "bmn", $month);
- $ilCtrl->setParameterByClass("ilblogpostinggui", "blpg", $id);
- $url = $ilCtrl->getLinkTargetByClass("ilblogpostinggui", $a_posting_cmd);
- }
- else
- {
- $url = $this->buildExportLink($a_link_template, "posting", $id);
- }
-
- if(!$posting["active"])
- {
- $wtpl->setVariable("NAV_ITEM_DRAFT", $this->lng->txt("blog_draft"));
- }
- else if($this->object->hasApproval() && !$posting["approved"])
- {
- $wtpl->setVariable("NAV_ITEM_APPROVAL", $this->lng->txt("blog_needs_approval"));
- }
-
- $wtpl->setCurrentBlock("navigation_item");
- $wtpl->setVariable("NAV_ITEM_URL", $url);
- $wtpl->setVariable("NAV_ITEM_CAPTION", $caption);
- $wtpl->parseCurrentBlock();
- }
-
- $wtpl->setCurrentBlock("navigation_month_details");
- if($blpg > 0)
- {
- $wtpl->setVariable("NAV_MONTH", $month_name);
- $wtpl->setVariable("URL_MONTH", $month_url);
- }
- $wtpl->parseCurrentBlock();
- }
- }
-
- if($blpg == 0)
- {
- $wtpl->setCurrentBlock("option_bl");
- foreach($month_options as $value => $caption)
- {
- $wtpl->setVariable("OPTION_VALUE", $value);
- $wtpl->setVariable("OPTION_CAPTION", $caption);
- if($value == $this->month)
- {
- $wtpl->setVariable("OPTION_SEL", ' selected="selected"');
- }
- $wtpl->parseCurrentBlock();
- }
-
- $wtpl->setVariable("FORM_ACTION", $ilCtrl->getFormAction($this, $a_list_cmd));
- }
-
- $ilCtrl->setParameter($this, "bmn", $this->month);
- $ilCtrl->setParameterByClass("ilblogpostinggui", "bmn", "");
-
- return $wtpl->get();
- }
- }
-
- /**
- * Build navigation by keywords block
- *
- * @param string $a_list_cmd
- * @param bool $a_show_inactive
- * @return string
- */
- protected function renderNavigationByKeywords($a_list_cmd = "render", $a_show_inactive = false, $a_link_template = false,
- $a_blpg = 0)
- {
- $ilCtrl = $this->ctrl;
-
- $blpg = ($a_blpg > 0)
- ? $a_blpg
- : $this->blpg;
-
- $keywords = $this->getKeywords($a_show_inactive, $blpg);
- if($keywords)
- {
- $wtpl = new ilTemplate("tpl.blog_list_navigation_keywords.html", true, true, "Modules/Blog");
-
- $max = max($keywords);
- include_once "Services/Tagging/classes/class.ilTagging.php";
-
- $wtpl->setCurrentBlock("keyword");
- foreach($keywords as $keyword => $counter)
- {
- if(!$a_link_template)
- {
- $ilCtrl->setParameter($this, "kwd", urlencode($keyword)); // #15885
- $url = $ilCtrl->getLinkTarget($this, $a_list_cmd);
- $ilCtrl->setParameter($this, "kwd", "");
- }
- else
- {
- $url = $this->buildExportLink($a_link_template, "keyword", $keyword);
- }
-
- $wtpl->setVariable("TXT_KEYWORD", $keyword);
- $wtpl->setVariable("CLASS_KEYWORD", ilTagging::getRelevanceClass($counter, $max));
- $wtpl->setVariable("URL_KEYWORD", $url);
- $wtpl->parseCurrentBlock();
- }
-
- return $wtpl->get();
- }
- }
-
- protected function renderNavigationByAuthors(array $a_items, $a_list_cmd = "render", $a_show_inactive = false)
- {
- $ilCtrl = $this->ctrl;
-
- $authors = array();
- foreach($a_items as $month => $items)
- {
- foreach($items as $item)
- {
- if(($a_show_inactive || ilBlogPosting::_lookupActive($item["id"], "blp")))
- {
- if($item["author"])
- {
- $authors[] = $item["author"];
- }
-
- if(is_array($item["editors"]))
- {
- foreach($item["editors"] as $editor_id)
- {
- if($editor_id != $item["author"])
- {
- $authors[] = $editor_id;
- }
- }
- }
- }
- }
- }
-
- $authors = array_unique($authors);
- if(sizeof($authors) > 1)
- {
- include_once "Services/User/classes/class.ilUserUtil.php";
-
- $list = array();
- foreach($authors as $user_id)
- {
- if($user_id)
- {
- $ilCtrl->setParameter($this, "ath", $user_id);
- $url = $ilCtrl->getLinkTarget($this, $a_list_cmd);
- $ilCtrl->setParameter($this, "ath", "");
-
- $name = ilUserUtil::getNamePresentation($user_id, true);
- $idx = trim(strip_tags($name))."///".$user_id; // #10934
- $list[$idx] = array($name, $url);
- }
- }
- ksort($list);
-
- $wtpl = new ilTemplate("tpl.blog_list_navigation_authors.html", true, true, "Modules/Blog");
-
- $wtpl->setCurrentBlock("author");
- foreach($list as $author)
- {
- $wtpl->setVariable("TXT_AUTHOR", $author[0]);
- $wtpl->setVariable("URL_AUTHOR", $author[1]);
- $wtpl->parseCurrentBlock();
- }
-
- return $wtpl->get();
- }
- }
-
- /**
- * Toolbar navigation
- *
- * @param
- * @return
- */
- function renderToolbarNavigation($a_items, $single_posting = false)
- {
- global $DIC;
-
- $toolbar = $DIC->toolbar();
- $lng = $DIC->language();
- $ctrl = $DIC->ctrl();
-
- $f = $DIC->ui()->factory();
-
- $cmd = ($this->prtf_embed)
+ $wtpl->setVariable("DATETIME", $author .
+ ilDatePresentation::formatDate($item["created"]) . $keywords);
+
+ // content
+ $wtpl->setVariable("CONTENT", $snippet);
+
+ $wtpl->parseCurrentBlock();
+ }
+
+ // permalink
+ if ($a_cmd == "previewFullscreen") {
+ $this->tpl->setPermanentLink(
+ "blog",
+ $this->node_id,
+ ($this->id_type == self::WORKSPACE_NODE_ID)
+ ? "_wsp"
+ : ""
+ );
+ }
+
+ if (!$is_empty || $a_show_inactive) {
+ return $wtpl->get();
+ }
+ }
+
+ /**
+ * Build navigation by date block
+ *
+ * @param array $a_items
+ * @param string $a_list_cmd
+ * @param string $a_posting_cmd
+ * @param bool $a_link_template
+ * @param bool $a_show_inactive
+ * @return string
+ */
+ protected function renderNavigationByDate(array $a_items, $a_list_cmd = "render", $a_posting_cmd = "preview", $a_link_template = null, $a_show_inactive = false, $a_blpg = 0)
+ {
+ $ilCtrl = $this->ctrl;
+
+ $blpg = ($a_blpg > 0)
+ ? $a_blpg
+ : $this->blpg;
+
+
+ // gather page active status
+ foreach ($a_items as $month => $postings) {
+ foreach (array_keys($postings) as $id) {
+ $active = ilBlogPosting::_lookupActive($id, "blp");
+ if (!$a_show_inactive && !$active) {
+ unset($a_items[$month][$id]);
+ } else {
+ $a_items[$month][$id]["active"] = $active;
+ }
+ }
+ if (!sizeof($a_items[$month])) {
+ unset($a_items[$month]);
+ }
+ }
+
+ // list month (incl. postings)
+ if ($this->object->getNavMode() == ilObjBlog::NAV_MODE_LIST || $a_link_template) {
+ //$max_detail_postings = $this->object->getNavModeListPostings();
+ $max_months = $this->object->getNavModeListMonths();
+
+ $wtpl = new ilTemplate("tpl.blog_list_navigation_by_date.html", true, true, "Modules/Blog");
+
+ $ilCtrl->setParameter($this, "blpg", "");
+
+ include_once "Services/Calendar/classes/class.ilCalendarUtil.php";
+ $counter = $mon_counter = $last_year = 0;
+ foreach ($a_items as $month => $postings) {
+ if (!$a_link_template && $max_months && $mon_counter >= $max_months) {
+ break;
+ }
+
+ $add_year = false;
+ $year = substr($month, 0, 4);
+ if (!$last_year || $year != $last_year) {
+ // #13562
+ $add_year = true;
+ $last_year = $year;
+ }
+
+ $mon_counter++;
+
+ $month_name = ilCalendarUtil::_numericMonthToString((int) substr($month, 5));
+
+ if (!$a_link_template) {
+ $ilCtrl->setParameter($this, "bmn", $month);
+ $month_url = $ilCtrl->getLinkTarget($this, $a_list_cmd);
+ } else {
+ $month_url = $this->buildExportLink($a_link_template, "list", $month);
+ }
+
+ // list postings for month
+ //if($counter < $max_detail_postings)
+ if ($mon_counter <= $this->object->getNavModeListMonthsWithPostings()) {
+ if ($add_year) {
+ $wtpl->setCurrentBlock("navigation_year_details");
+ $wtpl->setVariable("YEAR", $year);
+ $wtpl->parseCurrentBlock();
+ }
+
+ foreach ($postings as $id => $posting) {
+ //if($max_detail_postings && $counter >= $max_detail_postings)
+ //{
+ // break;
+ //}
+
+ $counter++;
+
+ $caption = /* ilDatePresentation::formatDate($posting["created"], IL_CAL_DATETIME).
+ ", ".*/ $posting["title"];
+
+ if (!$a_link_template) {
+ $ilCtrl->setParameterByClass("ilblogpostinggui", "bmn", $month);
+ $ilCtrl->setParameterByClass("ilblogpostinggui", "blpg", $id);
+ $url = $ilCtrl->getLinkTargetByClass("ilblogpostinggui", $a_posting_cmd);
+ } else {
+ $url = $this->buildExportLink($a_link_template, "posting", $id);
+ }
+
+ if (!$posting["active"]) {
+ $wtpl->setVariable("NAV_ITEM_DRAFT", $this->lng->txt("blog_draft"));
+ } elseif ($this->object->hasApproval() && !$posting["approved"]) {
+ $wtpl->setVariable("NAV_ITEM_APPROVAL", $this->lng->txt("blog_needs_approval"));
+ }
+
+ $wtpl->setCurrentBlock("navigation_item");
+ $wtpl->setVariable("NAV_ITEM_URL", $url);
+ $wtpl->setVariable("NAV_ITEM_CAPTION", $caption);
+ $wtpl->parseCurrentBlock();
+ }
+
+ $wtpl->setCurrentBlock("navigation_month_details");
+ $wtpl->setVariable("NAV_MONTH", $month_name);
+ $wtpl->setVariable("URL_MONTH", $month_url);
+ $wtpl->parseCurrentBlock();
+ }
+ // summarized month
+ else {
+ if ($add_year) {
+ $wtpl->setCurrentBlock("navigation_year");
+ $wtpl->setVariable("YEAR", $year);
+ $wtpl->parseCurrentBlock();
+ }
+
+ $wtpl->setCurrentBlock("navigation_month");
+ $wtpl->setVariable("MONTH_NAME", $month_name);
+ $wtpl->setVariable("URL_MONTH", $month_url);
+ $wtpl->setVariable("MONTH_COUNT", sizeof($postings));
+ $wtpl->parseCurrentBlock();
+ }
+ }
+
+ $ilCtrl->setParameter($this, "bmn", $this->month);
+ $ilCtrl->setParameterByClass("ilblogpostinggui", "bmn", "");
+
+ return $wtpl->get();
+ }
+ // single month
+ else {
+ $wtpl = new ilTemplate("tpl.blog_list_navigation_month.html", true, true, "Modules/Blog");
+
+ $ilCtrl->setParameter($this, "blpg", "");
+
+ include_once "Services/Calendar/classes/class.ilCalendarUtil.php";
+ $month_options = array();
+ foreach ($a_items as $month => $postings) {
+ $month_name = ilCalendarUtil::_numericMonthToString((int) substr($month, 5)) .
+ " " . substr($month, 0, 4);
+
+ $month_options[$month] = $month_name;
+
+ if ($month == $this->month) {
+ if (!$a_link_template) {
+ $ilCtrl->setParameter($this, "bmn", $month);
+ $month_url = $ilCtrl->getLinkTarget($this, $a_list_cmd);
+ } else {
+ $month_url = $this->buildExportLink($a_link_template, "list", $month);
+ }
+
+ foreach ($postings as $id => $posting) {
+ $caption = /* ilDatePresentation::formatDate($posting["created"], IL_CAL_DATETIME).
+ ", ".*/ $posting["title"];
+
+ if (!$a_link_template) {
+ $ilCtrl->setParameterByClass("ilblogpostinggui", "bmn", $month);
+ $ilCtrl->setParameterByClass("ilblogpostinggui", "blpg", $id);
+ $url = $ilCtrl->getLinkTargetByClass("ilblogpostinggui", $a_posting_cmd);
+ } else {
+ $url = $this->buildExportLink($a_link_template, "posting", $id);
+ }
+
+ if (!$posting["active"]) {
+ $wtpl->setVariable("NAV_ITEM_DRAFT", $this->lng->txt("blog_draft"));
+ } elseif ($this->object->hasApproval() && !$posting["approved"]) {
+ $wtpl->setVariable("NAV_ITEM_APPROVAL", $this->lng->txt("blog_needs_approval"));
+ }
+
+ $wtpl->setCurrentBlock("navigation_item");
+ $wtpl->setVariable("NAV_ITEM_URL", $url);
+ $wtpl->setVariable("NAV_ITEM_CAPTION", $caption);
+ $wtpl->parseCurrentBlock();
+ }
+
+ $wtpl->setCurrentBlock("navigation_month_details");
+ if ($blpg > 0) {
+ $wtpl->setVariable("NAV_MONTH", $month_name);
+ $wtpl->setVariable("URL_MONTH", $month_url);
+ }
+ $wtpl->parseCurrentBlock();
+ }
+ }
+
+ if ($blpg == 0) {
+ $wtpl->setCurrentBlock("option_bl");
+ foreach ($month_options as $value => $caption) {
+ $wtpl->setVariable("OPTION_VALUE", $value);
+ $wtpl->setVariable("OPTION_CAPTION", $caption);
+ if ($value == $this->month) {
+ $wtpl->setVariable("OPTION_SEL", ' selected="selected"');
+ }
+ $wtpl->parseCurrentBlock();
+ }
+
+ $wtpl->setVariable("FORM_ACTION", $ilCtrl->getFormAction($this, $a_list_cmd));
+ }
+
+ $ilCtrl->setParameter($this, "bmn", $this->month);
+ $ilCtrl->setParameterByClass("ilblogpostinggui", "bmn", "");
+
+ return $wtpl->get();
+ }
+ }
+
+ /**
+ * Build navigation by keywords block
+ *
+ * @param string $a_list_cmd
+ * @param bool $a_show_inactive
+ * @return string
+ */
+ protected function renderNavigationByKeywords(
+ $a_list_cmd = "render",
+ $a_show_inactive = false,
+ $a_link_template = false,
+ $a_blpg = 0
+ ) {
+ $ilCtrl = $this->ctrl;
+
+ $blpg = ($a_blpg > 0)
+ ? $a_blpg
+ : $this->blpg;
+
+ $keywords = $this->getKeywords($a_show_inactive, $blpg);
+ if ($keywords) {
+ $wtpl = new ilTemplate("tpl.blog_list_navigation_keywords.html", true, true, "Modules/Blog");
+
+ $max = max($keywords);
+ include_once "Services/Tagging/classes/class.ilTagging.php";
+
+ $wtpl->setCurrentBlock("keyword");
+ foreach ($keywords as $keyword => $counter) {
+ if (!$a_link_template) {
+ $ilCtrl->setParameter($this, "kwd", urlencode($keyword)); // #15885
+ $url = $ilCtrl->getLinkTarget($this, $a_list_cmd);
+ $ilCtrl->setParameter($this, "kwd", "");
+ } else {
+ $url = $this->buildExportLink($a_link_template, "keyword", $keyword);
+ }
+
+ $wtpl->setVariable("TXT_KEYWORD", $keyword);
+ $wtpl->setVariable("CLASS_KEYWORD", ilTagging::getRelevanceClass($counter, $max));
+ $wtpl->setVariable("URL_KEYWORD", $url);
+ $wtpl->parseCurrentBlock();
+ }
+
+ return $wtpl->get();
+ }
+ }
+
+ protected function renderNavigationByAuthors(array $a_items, $a_list_cmd = "render", $a_show_inactive = false)
+ {
+ $ilCtrl = $this->ctrl;
+
+ $authors = array();
+ foreach ($a_items as $month => $items) {
+ foreach ($items as $item) {
+ if (($a_show_inactive || ilBlogPosting::_lookupActive($item["id"], "blp"))) {
+ if ($item["author"]) {
+ $authors[] = $item["author"];
+ }
+
+ if (is_array($item["editors"])) {
+ foreach ($item["editors"] as $editor_id) {
+ if ($editor_id != $item["author"]) {
+ $authors[] = $editor_id;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ $authors = array_unique($authors);
+ if (sizeof($authors) > 1) {
+ include_once "Services/User/classes/class.ilUserUtil.php";
+
+ $list = array();
+ foreach ($authors as $user_id) {
+ if ($user_id) {
+ $ilCtrl->setParameter($this, "ath", $user_id);
+ $url = $ilCtrl->getLinkTarget($this, $a_list_cmd);
+ $ilCtrl->setParameter($this, "ath", "");
+
+ $name = ilUserUtil::getNamePresentation($user_id, true);
+ $idx = trim(strip_tags($name)) . "///" . $user_id; // #10934
+ $list[$idx] = array($name, $url);
+ }
+ }
+ ksort($list);
+
+ $wtpl = new ilTemplate("tpl.blog_list_navigation_authors.html", true, true, "Modules/Blog");
+
+ $wtpl->setCurrentBlock("author");
+ foreach ($list as $author) {
+ $wtpl->setVariable("TXT_AUTHOR", $author[0]);
+ $wtpl->setVariable("URL_AUTHOR", $author[1]);
+ $wtpl->parseCurrentBlock();
+ }
+
+ return $wtpl->get();
+ }
+ }
+
+ /**
+ * Toolbar navigation
+ *
+ * @param
+ * @return
+ */
+ public function renderToolbarNavigation($a_items, $single_posting = false)
+ {
+ global $DIC;
+
+ $toolbar = $DIC->toolbar();
+ $lng = $DIC->language();
+ $ctrl = $DIC->ctrl();
+
+ $f = $DIC->ui()->factory();
+
+ $cmd = ($this->prtf_embed)
? "previewEmbedded"
: "previewFullscreen";
- if ($single_posting) // single posting view
- {
- include_once "Services/Calendar/classes/class.ilCalendarUtil.php";
-
- $latest_posting = $this->getLatestPosting($a_items);
- if ($latest_posting != "" && $this->blpg != $latest_posting)
- {
- $ctrl->setParameterByClass("ilblogpostinggui", "blpg", $latest_posting);
- $mb = $f->button()->standard($lng->txt("blog_latest_posting"),
- $ctrl->getLinkTargetByClass("ilblogpostinggui", $cmd));
- }
- else
- {
- $mb = $f->button()->standard($lng->txt("blog_latest_posting"), "#")->withUnavailableAction();
- }
-
- $prev_posting = $this->getPreviousPosting($a_items);
- if ($prev_posting != "")
- {
- $ctrl->setParameterByClass("ilblogpostinggui", "blpg", $prev_posting);
- $pb = $f->button()->standard($lng->txt("previous"),
- $ctrl->getLinkTargetByClass("ilblogpostinggui", $cmd));
- } else
- {
- $pb = $f->button()->standard($lng->txt("previous"), "#")->withUnavailableAction();
- }
-
- $next_posting = $this->getNextPosting($a_items);
- if ($next_posting != "")
- {
- $ctrl->setParameterByClass("ilblogpostinggui", "blpg", $next_posting);
- $nb = $f->button()->standard($lng->txt("next"),
- $ctrl->getLinkTargetByClass("ilblogpostinggui", $cmd));
- } else
- {
- $nb = $f->button()->standard($lng->txt("next"), "#")->withUnavailableAction();
- }
- $ctrl->setParameter($this, "blpg", $this->blpg);
- $vc = $f->viewControl()->section($pb, $mb, $nb);
- $toolbar->addComponent($vc);
- }
- else // month view
- {
- include_once "Services/Calendar/classes/class.ilCalendarUtil.php";
-
- $latest_month = $this->getLatestMonth($a_items);
- if ($latest_month != "" && $this->month != $latest_month)
- {
- $ctrl->setParameter($this, "bmn", $latest_month);
- $mb = $f->button()->standard($lng->txt("blog_latest_posting"),
- $ctrl->getLinkTarget($this, "preview"));
- }
- else
- {
- $mb = $f->button()->standard($lng->txt("blog_latest_posting"), "#")->withUnavailableAction();
- }
-
- $prev_month = $this->getPreviousMonth($a_items);
- if ($prev_month != "")
- {
- $ctrl->setParameter($this, "bmn", $prev_month);
- $pb = $f->button()->standard($lng->txt("previous"), $ctrl->getLinkTarget($this, "preview"));
- } else
- {
- $pb = $f->button()->standard($lng->txt("previous"), "#")->withUnavailableAction();
- }
-
- $next_month = $this->getNextMonth($a_items);
- if ($next_month != "")
- {
- $ctrl->setParameter($this, "bmn", $next_month);
- $nb = $f->button()->standard($lng->txt("next"), $ctrl->getLinkTarget($this, "preview"));
- } else
- {
- $nb = $f->button()->standard($lng->txt("next"), "#")->withUnavailableAction();
- }
- $ctrl->setParameter($this, "bmn", $this->month);
- $vc = $f->viewControl()->section($pb, $mb, $nb);
- $toolbar->addComponent($vc);
- }
- }
-
- /**
- * Get next month
- *
- * @param array $a_items item array
- * @return string
- */
- function getNextMonth($a_items)
- {
- reset($a_items);
- $found = "";
- foreach ($a_items as $month => $items)
- {
- if ($month > $this->month)
- {
- $found = $month;
- }
- }
- return $found;
- }
-
- /**
- * Get next month
- *
- * @param array $a_items item array
- * @return string
- */
- function getPreviousMonth($a_items)
- {
- reset($a_items);
- $found = "";
- foreach ($a_items as $month => $items)
- {
- if ($month < $this->month && $found == "")
- {
- $found = $month;
- }
- }
- return $found;
- }
-
- /**
- * Get next month
- *
- * @param array $a_items item array
- * @return string
- */
- function getLatestMonth($a_items)
- {
- reset($a_items);
- return key($a_items);
- }
-
- /**
- * Get next posting
- *
- * @param array $a_items item array
- * @return int page id
- */
- function getNextPosting($a_items)
- {
- reset($a_items);
- $found = "";
- $next_blpg = 0;
- foreach ($a_items as $month => $items)
- {
- foreach ($items as $item)
- {
- if ($item["id"] == $this->blpg)
- {
- $found = true;
- }
- if (!$found)
- {
- $next_blpg = $item["id"];
- }
- }
- }
- return $next_blpg;
- }
-
- /**
- * Get previous posting
- *
- * @param array $a_items item array
- * @return int page id
- */
- function getPreviousPosting($a_items)
- {
- reset($a_items);
- $found = "";
- $prev_blpg = 0;
- foreach ($a_items as $month => $items)
- {
- foreach ($items as $item)
- {
- if ($found && $prev_blpg == "")
- {
- $prev_blpg = $item["id"];
- }
- if ($item["id"] == $this->blpg)
- {
- $found = true;
- }
- }
- }
- return $prev_blpg;
- }
-
- /**
- * Get previous posting
- *
- * @param array $a_items item array
- * @return int page id
- */
- function getLatestPosting($a_items)
- {
- reset($a_items);
- $month = current($a_items);
- if (is_array($month))
- {
- return current($month)["id"];
- }
- return false;
- }
-
- /**
- * Build navigation blocks
- *
- * @param array $a_items
- * @param string $a_list_cmd
- * @param string $a_posting_cmd
- * @param bool $a_link_template
- * @param bool $a_show_inactive
- * @param int $a_blpg blog page id
- * @return string
- */
- function renderNavigation(array $a_items, $a_list_cmd = "render", $a_posting_cmd = "preview", $a_link_template = null, $a_show_inactive = false, $a_blpg = 0)
- {
- $ilCtrl = $this->ctrl;
- $ilSetting = $this->settings;
-
- $blpg = ($a_blpg > 0)
- ? $a_blpg
- : $this->blpg;
-
- if($this->object->getOrder())
- {
- $order = array_flip($this->object->getOrder());
- }
- else
- {
- $order = array(
- "navigation" => 0
- ,"keywords" => 2
- ,"authors" => 1
- );
- }
-
- $wtpl = new ilTemplate("tpl.blog_list_navigation.html", true, true, "Modules/Blog");
-
- $blocks = array();
-
- // by date
- if(sizeof($a_items))
- {
- $blocks[$order["navigation"]] = array(
- $this->lng->txt("blog_navigation"),
- $this->renderNavigationByDate($a_items, $a_list_cmd, $a_posting_cmd, $a_link_template, $a_show_inactive, $a_blpg)
- );
- }
-
- if($this->object->hasKeywords())
- {
- // keywords
- $may_edit_keywords = ($blpg > 0 &&
- $this->mayEditPosting($blpg) &&
- $a_list_cmd != "preview" &&
- $a_list_cmd != "gethtml" &&
- !$a_link_template);
- $keywords = $this->renderNavigationByKeywords($a_list_cmd, $a_show_inactive, $a_link_template, $a_blpg);
- if($keywords || $may_edit_keywords)
- {
- if(!$keywords)
- {
- $keywords = $this->lng->txt("blog_no_keywords");
- }
- $cmd = null;
- $blocks[$order["keywords"]] = array(
- $this->lng->txt("blog_keywords"),
- $keywords,
- $cmd
- ? array($cmd, $this->lng->txt("blog_edit_keywords"))
- : null
- );
- }
- }
-
- // is not part of (html) export
- if(!$a_link_template)
- {
- // authors
- if($this->id_type == self::REPOSITORY_NODE_ID &&
- $this->object->hasAuthors())
- {
- $authors = $this->renderNavigationByAuthors($a_items, $a_list_cmd, $a_show_inactive);
- if($authors)
- {
- $blocks[$order["authors"]] = array($this->lng->txt("blog_authors"), $authors);
- }
- }
-
- // rss
- if($this->object->hasRSS() &&
- $ilSetting->get('enable_global_profiles') &&
- $a_list_cmd == "preview")
- {
- // #10827
- $blog_id = $this->node_id;
- if($this->id_type != self::WORKSPACE_NODE_ID)
- {
- $blog_id .= "_cll";
- }
- $url = ILIAS_HTTP_PATH."/feed.php?blog_id=".$blog_id.
- "&client_id=".rawurlencode(CLIENT_ID);
-
- include_once("./Services/News/classes/class.ilRSSButtonGUI.php");
- $wtpl->setVariable("RSS_BUTTON", ilRSSButtonGUI::get(ilRSSButtonGUI::ICON_RSS, $url));
- }
- }
-
- if(sizeof($blocks))
- {
- include_once "Services/UIComponent/Panel/classes/class.ilPanelGUI.php";
-
- ksort($blocks);
- foreach($blocks as $block)
- {
- $panel = ilPanelGUI::getInstance();
- $panel->setPanelStyle(ilPanelGUI::PANEL_STYLE_SECONDARY);
- $panel->setHeadingStyle(ilPanelGUI::HEADING_STYLE_BLOCK);
- $panel->setHeading($block[0]);
- $panel->setBody($block[1]);
-
- if(isset($block[2]) && is_array($block[2]))
- {
- $panel->setFooter(''.$block[2][1].'');
- }
-
- $wtpl->setCurrentBlock("block_bl");
- $wtpl->setVariable("BLOCK", $panel->getHTML());
- $wtpl->parseCurrentBlock();
- }
- }
-
- return $wtpl->get();
- }
-
- /**
- * Get keywords for single posting or complete blog
- *
- * @param bool $a_show_inactive
- * @param int $a_posting_id
- * @return array
- */
- function getKeywords($a_show_inactive, $a_posting_id = null)
- {
- $keywords = array();
- include_once("./Modules/Blog/classes/class.ilBlogPosting.php");
- if($a_posting_id)
- {
- foreach(ilBlogPosting::getKeywords($this->obj_id, $a_posting_id) as $keyword)
- {
- $keywords[$keyword]++;
- }
- }
- else
- {
- foreach($this->items as $month => $items)
- {
- foreach($items as $item)
- {
- if($a_show_inactive || ilBlogPosting::_lookupActive($item["id"], "blp"))
- {
- foreach(ilBlogPosting::getKeywords($this->obj_id, $item["id"]) as $keyword)
- {
- $keywords[$keyword]++;
- }
- }
- }
- }
- }
-
- // #15881
- $tmp = array();
- foreach($keywords as $keyword => $counter)
- {
- $tmp[] = array("keyword"=>$keyword, "counter"=>$counter);
- }
- $tmp = ilUtil::sortArray($tmp, "keyword", "ASC");
-
- $keywords = array();
- foreach($tmp as $item)
- {
- $keywords[$item["keyword"]] = $item["counter"];
- }
- return $keywords;
- }
-
- /**
- * Build export file
- *
- * @return string
- */
- function buildExportFile()
- {
- // create export file
- include_once("./Services/Export/classes/class.ilExport.php");
- ilExport::_createExportDirectory($this->object->getId(), "html", "blog");
- $exp_dir = ilExport::_getExportDirectory($this->object->getId(), "html", "blog");
-
- $subdir = $this->object->getType()."_".$this->object->getId();
- $export_dir = $exp_dir."/".$subdir;
-
- // initialize temporary target directory
- ilUtil::delDir($export_dir);
- ilUtil::makeDir($export_dir);
-
- // system style html exporter
- include_once("./Services/Style/System/classes/class.ilSystemStyleHTMLExport.php");
- $this->sys_style_html_export = new ilSystemStyleHTMLExport($export_dir);
- $this->sys_style_html_export->addImage("icon_blog.svg");
- $this->sys_style_html_export->export();
-
- // init co page html exporter
- include_once("./Services/COPage/classes/class.ilCOPageHTMLExport.php");
- $this->co_page_html_export = new ilCOPageHTMLExport($export_dir);
- $this->co_page_html_export->setContentStyleId($this->object->getStyleSheetId());
- $this->co_page_html_export->createDirectories();
- $this->co_page_html_export->exportStyles();
- $this->co_page_html_export->exportSupportScripts();
-
- // banner / profile picture
- $blga_set = new ilSetting("blga");
- if($blga_set->get("banner"))
- {
- $banner = $this->object->getImageFullPath();
- if($banner)
- {
- copy($banner, $export_dir."/".basename($banner));
- }
- }
- $ppic = ilObjUser::_getPersonalPicturePath($this->object->getOwner(), "xsmall", true, true);
- if($ppic)
- {
- $ppic = array_shift(explode("?", $ppic));
- copy($ppic, $export_dir."/".basename($ppic));
- }
-
- // export pages
- $this->exportHTMLPages($export_dir);
-
- // zip everything
- if (true)
- {
- // zip it all
- $date = time();
- $zip_file = ilExport::_getExportDirectory($this->object->getId(), "html", "blog").
- "/".$date."__".IL_INST_ID."__".
- $this->object->getType()."_".$this->object->getId().".zip";
- ilUtil::zip($export_dir, $zip_file);
- ilUtil::delDir($export_dir);
- }
-
- return $zip_file;
- }
-
- /**
- * Export all pages
- *
- * @param string $a_target_directory
- * @param string $a_link_template (embedded)
- * @param array $a_tpl_callback (embedded)
- * @param object $a_co_page_html_export (embedded)
- * @param string $a_index_name (embedded)
- */
- function exportHTMLPages($a_target_directory, $a_link_template = null, $a_tpl_callback = null, $a_co_page_html_export = null, $a_index_name = "index.html")
- {
- require_once('Services/MathJax/classes/class.ilMathJax.php');
- ilMathJax::getInstance()->init(ilMathJax::PURPOSE_EXPORT);
-
- if(!$a_link_template)
- {
- $a_link_template = "bl{TYPE}_{ID}.html";
- }
-
- if($a_co_page_html_export)
- {
- $this->co_page_html_export = $a_co_page_html_export;
- }
-
-
- // lists
-
- // global nav
- $nav = $this->renderNavigation($this->items, "", "", $a_link_template);
-
- // month list
- $has_index = false;
- foreach(array_keys($this->items) as $month)
- {
- $list = $this->renderList($this->items[$month], "render", $a_link_template, false, $a_target_directory);
-
- if(!$list)
- {
- continue;
- }
-
- if(!$a_tpl_callback)
- {
- $tpl = $this->buildExportTemplate();
- }
- else
- {
- $tpl = call_user_func($a_tpl_callback);
- }
-
- $file = $this->buildExportLink($a_link_template, "list", $month);
- $file = $this->writeExportFile($a_target_directory, $file,
- $tpl, $list, $nav);
-
- if(!$has_index)
- {
- copy($file, $a_target_directory."/".$a_index_name);
- $has_index = true;
- }
- }
-
- // keywords
- foreach(array_keys($this->getKeywords(false)) as $keyword)
- {
- $this->keyword = $keyword;
- $list_items = $this->filterItemsByKeyword($this->items, $keyword);
- $list = $this->renderList($list_items, "render", $a_link_template, false, $a_target_directory);
-
- if(!$list)
- {
- continue;
- }
-
- if(!$a_tpl_callback)
- {
- $tpl = $this->buildExportTemplate();
- }
- else
- {
- $tpl = call_user_func($a_tpl_callback);
- }
-
- $file = $this->buildExportLink($a_link_template, "keyword", $keyword);
- $file = $this->writeExportFile($a_target_directory, $file,
- $tpl, $list, $nav);
- }
-
-
- // single postings
-
- include_once("./Services/COPage/classes/class.ilPageContentUsage.php");
- include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php");
- $pages = ilBlogPosting::getAllPostings($this->object->getId(), 0);
- foreach ($pages as $page)
- {
- if (ilBlogPosting::_exists("blp", $page["id"]))
- {
- include_once("./Modules/Blog/classes/class.ilBlogPostingGUI.php");
- $blp_gui = new ilBlogPostingGUI(0, null, $page["id"]);
- $blp_gui->setOutputMode("offline");
- $blp_gui->setFullscreenLink("fullscreen.html"); // #12930 - see page.xsl
- $blp_gui->add_date = true;
- $page_content = $blp_gui->showPage();
-
- $back = $this->buildExportLink($a_link_template, "list",
- substr($page["created"]->get(IL_CAL_DATE), 0, 7));
-
- $file = $this->buildExportLink($a_link_template, "posting", $page["id"]);
-
- if(!$a_tpl_callback)
- {
- $tpl = $this->buildExportTemplate();
- }
- else
- {
- $tpl = call_user_func($a_tpl_callback);
- }
-
- // posting nav
- $nav = $this->renderNavigation($this->items, "", "", $a_link_template,
- false, $page["id"]);
-
- $this->writeExportFile($a_target_directory, $file, $tpl,
- $page_content, $nav, $back);
-
- $this->co_page_html_export->collectPageElements("blp:pg", $page["id"]);
- }
- }
- $this->co_page_html_export->exportPageElements();
- }
-
- /**
- * Build static export link
- *
- * @param string $a_template
- * @param string $a_type
- * @param mixed $a_id
- * @return string
- */
- protected function buildExportLink($a_template, $a_type, $a_id)
- {
- switch($a_type)
- {
- case "list":
- $a_type = "m";
- break;
- break;
-
- case "keyword":
- if(!self::$keyword_export_map)
- {
- self::$keyword_export_map = array_flip(array_keys($this->getKeywords(false)));
- }
- $a_id = self::$keyword_export_map[$a_id];
- $a_type = "k";
- break;
-
- default:
- $a_type = "p";
- break;
- }
-
- $link = str_replace("{TYPE}", $a_type, $a_template);
- return str_replace("{ID}", $a_id, $link);
- }
-
- /**
- * Build export "frame"
- *
- * @param type $a_back_url
- * @return ilTemplate
- */
- protected function buildExportTemplate($a_back_url = "")
- {
- $ilTabs = $this->tabs;
- $lng = $this->lng;
-
- $tpl = $this->co_page_html_export->getPreparedMainTemplate();
-
- $tpl->getStandardTemplate();
-
- $ilTabs->clearTargets();
- if($a_back_url)
- {
- $ilTabs->setBackTarget($lng->txt("back"), $a_back_url);
- }
-
- $this->renderFullscreenHeader($tpl, $this->object->getOwner(), true);
-
- return $tpl;
- }
-
- /**
- * Write HTML to file
- *
- * @param type $a_target_directory
- * @param type $a_file
- * @param type $a_tpl
- * @param type $a_content
- * @param type $a_right_content
- * @return string
- */
- protected function writeExportFile($a_target_directory, $a_file, $a_tpl, $a_content, $a_right_content = null, $a_back = null)
- {
- $file = $a_target_directory."/".$a_file;
- // return if file is already existing
- if (@is_file($file))
- {
- return;
- }
-
- // export template: page content
- $ep_tpl = new ilTemplate("tpl.export_page.html", true, true,
- "Modules/Blog");
- if($a_back)
- {
- $ep_tpl->setVariable("PAGE_CONTENT", $a_content);
- }
- else
- {
- $ep_tpl->setVariable("LIST", $a_content);
- }
- unset($a_content);
- $a_tpl->setContent($ep_tpl->get());
- unset($ep_tpl);
-
- // template: right content
- if($a_right_content)
- {
- $a_tpl->setRightContent($a_right_content);
- unset($a_right_content);
- }
-
- $content = $a_tpl->get("DEFAULT", false, false, false,
- true, true, true);
-
- // open file
- if (!file_put_contents($file, $content))
- {
- die ("Error: Could not open \"".$file."\" for writing".
- " in ".__FILE__." on line ".__LINE__."
");
- }
-
- // set file permissions
- chmod($file, 0770);
-
- return $file;
- }
-
- function getNotesSubId()
- {
- return $this->blpg;
- }
-
- function disableNotes($a_value = false)
- {
- $this->disable_notes = (bool)$a_value;
- }
-
- protected function addHeaderActionForCommand($a_cmd)
- {
- $ilUser = $this->user;
- $ilCtrl = $this->ctrl;
-
- // preview?
- if($a_cmd == "preview" || $a_cmd == "previewFullscreen" || $this->prvm)
- {
- // notification
- if($ilUser->getId() != ANONYMOUS_USER_ID)
- {
- if(!$this->prvm)
- {
- $ilCtrl->setParameter($this, "prvm", "fsc");
- }
- $this->insertHeaderAction($this->initHeaderAction(null, null, true));
- if(!$this->prvm)
- {
- $ilCtrl->setParameter($this, "prvm", "");
- }
- }
- }
- else
- {
- return parent::addHeaderAction();
- }
- }
-
- protected function initHeaderAction($sub_type = null, $sub_id = null, $a_is_preview = false)
- {
- $ilUser = $this->user;
- $ilCtrl = $this->ctrl;
-
- if(!$this->obj_id)
- {
- return false;
- }
-
- $sub_type = $sub_id = null;
- if($this->blpg > 0)
- {
- $sub_type = "blp";
- $sub_id = $this->blpg;
- }
-
- $lg = parent::initHeaderAction($sub_type, $sub_id);
-
- if($a_is_preview)
- {
- $lg->enableComments(false);
- $lg->enableNotes(false);
- $lg->enableTags(false);
-
- include_once "./Services/Notification/classes/class.ilNotification.php";
- if(ilNotification::hasNotification(ilNotification::TYPE_BLOG, $ilUser->getId(), $this->obj_id))
- {
- $ilCtrl->setParameter($this, "ntf", 1);
- $link = $ilCtrl->getLinkTarget($this, "setNotification");
- $ilCtrl->setParameter($this, "ntf", "");
- if (ilNotification::hasOptOut($this->obj_id))
- {
- $lg->addCustomCommand($link, "blog_notification_toggle_off");
- }
-
- $lg->addHeaderIcon("not_icon",
- ilUtil::getImagePath("notification_on.svg"),
- $this->lng->txt("blog_notification_activated"));
- }
- else
- {
- $ilCtrl->setParameter($this, "ntf", 2);
- $link = $ilCtrl->getLinkTarget($this, "setNotification");
- $ilCtrl->setParameter($this, "ntf", "");
- $lg->addCustomCommand($link, "blog_notification_toggle_on");
-
- $lg->addHeaderIcon("not_icon",
- ilUtil::getImagePath("notification_off.svg"),
- $this->lng->txt("blog_notification_deactivated"));
- }
-
- // #11758
- if($this->mayContribute())
- {
- $ilCtrl->setParameter($this, "prvm", "");
-
- $ilCtrl->setParameter($this, "bmn", "");
- $ilCtrl->setParameter($this, "blpg", "");
- $link = $ilCtrl->getLinkTarget($this, "");
- $ilCtrl->setParameter($this, "blpg", $sub_id);
- $ilCtrl->setParameter($this, "bmn", $this->month);
- $lg->addCustomCommand($link, "blog_edit"); // #11868
-
- if($sub_id && $this->mayEditPosting($sub_id))
- {
- $link = $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "edit");
- $lg->addCustomCommand($link, "blog_edit_posting");
- }
-
- $ilCtrl->setParameter($this, "prvm", "fsc");
- }
-
- $ilCtrl->setParameter($this, "ntf", "");
- }
-
- return $lg;
- }
-
- protected function setNotification()
- {
- $ilUser = $this->user;
- $ilCtrl = $this->ctrl;
-
- include_once "./Services/Notification/classes/class.ilNotification.php";
- switch($this->ntf)
- {
- case 1:
- ilNotification::setNotification(ilNotification::TYPE_BLOG, $ilUser->getId(), $this->obj_id, false);
- break;
-
- case 2:
- ilNotification::setNotification(ilNotification::TYPE_BLOG, $ilUser->getId(), $this->obj_id, true);
- break;
- }
-
- $ilCtrl->redirect($this, "preview");
- }
-
- /**
- * Get title for blog posting (used in ilNotesGUI)
- *
- * @param int $a_blog_id
- * @param int $a_posting_id
- * @return string
- */
- static function lookupSubObjectTitle($a_blog_id, $a_posting_id)
- {
- // page might be deleted, so setting halt on errors to false
- include_once "Modules/Blog/classes/class.ilBlogPosting.php";
- $post = new ilBlogPosting($a_posting_id);
- if($post->getBlogId() == $a_blog_id)
- {
- return $post->getTitle();
- }
- }
-
- /**
- * Filter inactive items from items list
- *
- * @return array
- */
- protected function filterInactivePostings()
- {
- foreach($this->items as $month => $postings)
- {
- foreach($postings as $id => $item)
- {
- if(!ilBlogPosting::_lookupActive($id, "blp"))
- {
- unset($this->items[$month][$id]);
- }
- else if($this->object->hasApproval() && !$item["approved"])
- {
- unset($this->items[$month][$id]);
- }
- }
- if(!sizeof($this->items[$month]))
- {
- unset($this->items[$month]);
- }
- }
-
- if($this->items && !isset($this->items[$this->month]))
- {
- $this->month = array_shift(array_keys($this->items));
- }
- }
-
- protected function filterItemsByKeyWord(array $a_items, $a_keyword)
- {
- $res = array();
- include_once("./Modules/Blog/classes/class.ilBlogPosting.php");
- foreach($a_items as $month => $items)
- {
- foreach($items as $item)
- {
- if(in_array($a_keyword,
- ilBlogPosting::getKeywords($this->obj_id, $item["id"])))
- {
- $res[] = $item;
- }
- }
- }
- return $res;
- }
-
- /**
- * Check if user has admin access (approve, may edit & deactivate all postings)
- *
- * @return bool
- */
- protected function isAdmin()
- {
- return ($this->checkPermissionBool("redact") ||
- $this->checkPermissionBool("write"));
- }
-
- /**
- * Check if user may edit posting
- *
- * @param int $a_posting_id
- * @param int $a_author_id
- * @return boolean
- */
- protected function mayEditPosting($a_posting_id, $a_author_id = null)
- {
- $ilUser = $this->user;
-
- // single author blog (owner) in personal workspace
- if($this->id_type == self::WORKSPACE_NODE_ID)
- {
- return $this->checkPermissionBool("write");
- }
-
- // repository blogs
-
- // redact allows to edit all postings
- if($this->checkPermissionBool("redact"))
- {
- return true;
- }
-
- // contribute gives access to own postings
- if($this->checkPermissionBool("contribute"))
- {
- // check owner of posting
- if(!$a_author_id)
- {
- include_once "Modules/Blog/classes/class.ilBlogPosting.php";
- $post = new ilBlogPosting($a_posting_id);
- $a_author_id = $post->getAuthor();
- }
- if($ilUser->getId() == $a_author_id)
- {
- return true;
- }
- else
- {
- return false;
- }
-
- return true;
- }
- return false;
- }
-
- /**
- * Check if user may contribute at all
- *
- * @return boolean
- */
- protected function mayContribute()
- {
- // single author blog (owner) in personal workspace
- if($this->id_type == self::WORKSPACE_NODE_ID)
- {
- return $this->checkPermissionBool("write");
- }
-
- return ($this->checkPermissionBool("redact") ||
- $this->checkPermissionBool("contribute"));
- }
-
- function addLocatorItems()
- {
- $ilLocator = $this->locator;
-
- if (is_object($this->object))
- {
- $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, ""), "", $this->node_id);
- }
- }
-
- function approve()
- {
- if($this->isAdmin() && $this->apid > 0)
- {
- include_once "Modules/Blog/classes/class.ilBlogPosting.php";
- $post = new ilBlogPosting($this->apid);
- $post->setApproved(true);
- $post->setBlogNodeId($this->node_id, ($this->id_type == self::WORKSPACE_NODE_ID));
- $post->update(true, false, true, "new"); // #13434
-
- ilUtil::sendSuccess($this->lng->txt("settings_saved"), true);
- }
-
- $this->ctrl->redirect($this, "render");
- }
-
-
- //
- // contributors
- //
-
- function contributors()
- {
- $ilTabs = $this->tabs;
- $ilToolbar = $this->toolbar;
- $ilCtrl = $this->ctrl;
- $lng = $this->lng;
- $tpl = $this->tpl;
-
- if(!$this->checkPermissionBool("write"))
- {
- return;
- }
-
- $ilTabs->activateTab("contributors");
-
- $local_roles = $this->object->getAllLocalRoles($this->node_id);
-
- // add member
- include_once './Services/Search/classes/class.ilRepositorySearchGUI.php';
- ilRepositorySearchGUI::fillAutoCompleteToolbar(
- $this,
- $ilToolbar,
- array(
- 'auto_complete_name' => $lng->txt('user'),
- 'submit_name' => $lng->txt('add'),
- 'add_search' => true,
- 'add_from_container' => $this->node_id,
- 'user_type' => $local_roles
- ),
- true
- );
-
- $other_roles = $this->object->getRolesWithContributeOrRedact($this->node_id);
- if($other_roles)
- {
- ilUtil::sendInfo(sprintf($lng->txt("blog_contribute_other_roles"), implode(", ", $other_roles)));
- }
-
- include_once "Modules/Blog/classes/class.ilContributorTableGUI.php";
- $tbl = new ilContributorTableGUI($this, "contributors", $this->object->getAllLocalRoles($this->node_id));
-
- $tpl->setContent($tbl->getHTML());
- }
-
- /**
- * Autocomplete submit
- */
- public function addUserFromAutoComplete()
- {
- $lng = $this->lng;
-
- $user_login = ilUtil::stripSlashes($_POST['user_login']);
- $user_type = ilUtil::stripSlashes($_POST["user_type"]);
-
- if(!strlen(trim($user_login)))
- {
- ilUtil::sendFailure($lng->txt('msg_no_search_string'));
- return $this->contributors();
- }
- $users = explode(',', $user_login);
-
- $user_ids = array();
- foreach($users as $user)
- {
- $user_id = ilObjUser::_lookupId($user);
-
- if(!$user_id)
- {
- ilUtil::sendFailure($lng->txt('user_not_known'));
- return $this->contributors();
- }
-
- $user_ids[] = $user_id;
- }
-
- return $this->addContributor($user_ids, $user_type);
- }
-
- /**
- * Centralized method to add contributors
- *
- * @param array $a_user_ids
- */
- public function addContributor($a_user_ids = array(), $a_user_type = null)
- {
- $ilCtrl = $this->ctrl;
- $lng = $this->lng;
- $rbacreview = $this->rbacreview;
- $rbacadmin = $this->rbacadmin;
-
- if(!$this->checkPermissionBool("write"))
- {
- return;
- }
-
- if(!count($a_user_ids) || !$a_user_type)
- {
- ilUtil::sendFailure($lng->txt("no_checkbox"));
- return $this->contributors();
- }
-
- // get contributor role
- $local_roles = array_keys($this->object->getAllLocalRoles($this->node_id));
- if(!in_array($a_user_type, $local_roles))
- {
- ilUtil::sendFailure($lng->txt("missing_perm"));
- return $this->contributors();
- }
-
- foreach($a_user_ids as $user_id)
- {
- if(!$rbacreview->isAssigned($user_id, $a_user_type))
- {
- $rbacadmin->assignUser($a_user_type, $user_id);
- }
- }
-
- ilUtil::sendSuccess($lng->txt("settings_saved"), true);
- $ilCtrl->redirect($this, "contributors");
- }
-
- /**
- * Used in ilContributorTableGUI
- */
- public function confirmRemoveContributor()
- {
- $ids = ilUtil::stripSlashesRecursive($_POST["id"]);
-
- if(!is_array($ids))
- {
- ilUtil::sendFailure($this->lng->txt("select_one"), true);
- $this->ctrl->redirect($this, "contributors");
- }
-
- include_once './Services/Utilities/classes/class.ilConfirmationGUI.php';
- $confirm = new ilConfirmationGUI();
- $confirm->setHeaderText($this->lng->txt('blog_confirm_delete_contributors'));
- $confirm->setFormAction($this->ctrl->getFormAction($this, 'removeContributor'));
- $confirm->setConfirm($this->lng->txt('delete'), 'removeContributor');
- $confirm->setCancel($this->lng->txt('cancel'), 'contributors');
-
- include_once 'Services/User/classes/class.ilUserUtil.php';
-
- foreach($ids as $user_id)
- {
- $confirm->addItem('id[]', $user_id,
- ilUserUtil::getNamePresentation($user_id, false, false, "", true));
- }
-
- $this->tpl->setContent($confirm->getHTML());
- }
-
- /**
- * Used in ilContributorTableGUI
- */
- public function removeContributor()
- {
- $ilCtrl = $this->ctrl;
- $lng = $this->lng;
- $rbacadmin = $this->rbacadmin;
-
- $ids = ilUtil::stripSlashesRecursive($_POST["id"]);
-
- if(!is_array($ids))
- {
- ilUtil::sendFailure($lng->txt("select_one"), true);
- $ilCtrl->redirect($this, "contributors");
- }
-
- // get contributor role
- $local_roles = array_keys($this->object->getAllLocalRoles($this->node_id));
- if(!$local_roles)
- {
- ilUtil::sendFailure($lng->txt("missing_perm"));
- return $this->contributors();
- }
-
- foreach($ids as $user_id)
- {
- foreach($local_roles as $role_id)
- {
- $rbacadmin->deassignUser($role_id, $user_id);
- }
- }
-
- ilUtil::sendSuccess($lng->txt("settings_saved"), true);
- $this->ctrl->redirect($this, "contributors");
- }
-
- /**
- * @see ilDesktopItemHandling::addToDesk()
- */
- public function addToDeskObject()
- {
- $lng = $this->lng;
-
- include_once './Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php';
- ilDesktopItemGUI::addToDesktop();
- ilUtil::sendSuccess($lng->txt("added_to_desktop"));
- }
-
- /**
- * @see ilDesktopItemHandling::removeFromDesk()
- */
- public function removeFromDeskObject()
- {
- $lng = $this->lng;
-
- include_once './Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php';
- ilDesktopItemGUI::removeFromDesktop();
- ilUtil::sendSuccess($lng->txt("removed_from_desktop"));
- }
-
- public function deactivateAdmin()
- {
- if($this->checkPermissionBool("write") && $this->apid > 0)
- {
- // ilBlogPostingGUI::deactivatePage()
- include_once "Modules/Blog/classes/class.ilBlogPosting.php";
- $post = new ilBlogPosting($this->apid);
- $post->setApproved(false);
- $post->setActive(false);
- $post->update(true, false, false);
-
- ilUtil::sendSuccess($this->lng->txt("settings_saved"), true);
- }
-
- $this->ctrl->redirect($this, "render");
- }
-
-
- ////
- //// Style related functions
- ////
-
- function setContentStyleSheet($a_tpl = null)
- {
- $tpl = $this->tpl;
-
- if ($a_tpl != null)
- {
- $ctpl = $a_tpl;
- }
- else
- {
- $ctpl = $tpl;
- }
-
- $ctpl->setCurrentBlock("ContentStyle");
- $ctpl->setVariable("LOCATION_CONTENT_STYLESHEET",
- ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId()));
- $ctpl->parseCurrentBlock();
- }
-
- function editStyleProperties()
- {
- $this->checkPermission("write");
-
- $this->tabs_gui->activateTab("settings");
- $this->setSettingsSubTabs("style");
-
- $form = $this->initStylePropertiesForm();
- $this->tpl->setContent($form->getHTML());
- }
-
- function initStylePropertiesForm()
- {
- $ilSetting = $this->settings;
-
- include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php");
- $this->lng->loadLanguageModule("style");
-
- include_once("./Services/Form/classes/class.ilPropertyFormGUI.php");
- $form = new ilPropertyFormGUI();
-
- $fixed_style = $ilSetting->get("fixed_content_style_id");
- $style_id = $this->object->getStyleSheetId();
-
- if ($fixed_style > 0)
- {
- $st = new ilNonEditableValueGUI($this->lng->txt("style_current_style"));
- $st->setValue(ilObject::_lookupTitle($fixed_style)." (".
- $this->lng->txt("global_fixed").")");
- $form->addItem($st);
- }
- else
- {
- $st_styles = ilObjStyleSheet::_getStandardStyles(true, false,
- $this->ref_id);
-
- $st_styles[0] = $this->lng->txt("default");
- ksort($st_styles);
-
- if ($style_id > 0)
- {
- // individual style
- if (!ilObjStyleSheet::_lookupStandard($style_id))
- {
- $st = new ilNonEditableValueGUI($this->lng->txt("style_current_style"));
- $st->setValue(ilObject::_lookupTitle($style_id));
- $form->addItem($st);
-
- // delete command
- $form->addCommandButton("editStyle", $this->lng->txt("style_edit_style"));
- $form->addCommandButton("deleteStyle", $this->lng->txt("style_delete_style"));
- }
- }
-
- if ($style_id <= 0 || ilObjStyleSheet::_lookupStandard($style_id))
- {
- $style_sel = new ilSelectInputGUI($this->lng->txt("style_current_style"),
- "style_id");
- $style_sel->setOptions($st_styles);
- $style_sel->setValue($style_id);
- $form->addItem($style_sel);
-
- $form->addCommandButton("saveStyleSettings", $this->lng->txt("save"));
- $form->addCommandButton("createStyle", $this->lng->txt("sty_create_ind_style"));
- }
- }
-
- $form->setTitle($this->lng->txt("blog_style"));
- $form->setFormAction($this->ctrl->getFormAction($this));
-
- return $form;
- }
-
- function createStyle()
- {
- $this->ctrl->redirectByClass("ilobjstylesheetgui", "create");
- }
-
- function editStyle()
- {
- $this->ctrl->redirectByClass("ilobjstylesheetgui", "edit");
- }
-
- function deleteStyle()
- {
- $this->ctrl->redirectByClass("ilobjstylesheetgui", "delete");
- }
-
- function saveStyleSettings()
- {
- $ilSetting = $this->settings;
-
- include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php");
- if ($ilSetting->get("fixed_content_style_id") <= 0 &&
- (ilObjStyleSheet::_lookupStandard($this->object->getStyleSheetId())
- || $this->object->getStyleSheetId() == 0))
- {
- $this->object->setStyleSheetId((int) $_POST["style_id"]);
- $this->object->update();
-
- ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true);
- }
- $this->ctrl->redirect($this, "editStyleProperties");
- }
-
- /**
- * Deep link
- *
- * @param string $a_target
- */
- public static function _goto($a_target)
- {
- global $DIC;
-
- $ilCtrl = $DIC->ctrl();
-
- if(substr($a_target, -3) == "wsp")
- {
- $id = explode("_", $a_target);
-
- $ilCtrl->setTargetScript("ilias.php");
- $ilCtrl->initBaseClass("ilSharedResourceGUI");
- $ilCtrl->setParameterByClass("ilSharedResourceGUI", "wsp_id", $id[0]);
-
- if(sizeof($id) >= 2)
- {
- if(is_numeric($id[1]))
- {
- $ilCtrl->setParameterByClass("ilSharedResourceGUI", "gtp", $id[1]);
- }
- else
- {
- $ilCtrl->setParameterByClass("ilSharedResourceGUI", "kwd", $id[1]);
- }
- }
- $ilCtrl->redirectByClass("ilSharedResourceGUI", "");
- }
- else
- {
- $id = explode("_", $a_target);
-
- $ilCtrl->setTargetScript("ilias.php");
- $ilCtrl->initBaseClass("ilRepositoryGUI");
- $ilCtrl->setParameterByClass("ilRepositoryGUI", "ref_id", $id[0]);
-
- if(sizeof($id) == 2)
- {
- if(is_numeric($id[1]))
- {
- $ilCtrl->setParameterByClass("ilRepositoryGUI", "gtp", $id[1]);
- }
- else
- {
- $ilCtrl->setParameterByClass("ilRepositoryGUI", "kwd", $id[1]);
- }
- }
- $ilCtrl->redirectByClass("ilRepositoryGUI", "preview");
- }
- }
+ if ($single_posting) { // single posting view
+ include_once "Services/Calendar/classes/class.ilCalendarUtil.php";
+
+ $latest_posting = $this->getLatestPosting($a_items);
+ if ($latest_posting != "" && $this->blpg != $latest_posting) {
+ $ctrl->setParameterByClass("ilblogpostinggui", "blpg", $latest_posting);
+ $mb = $f->button()->standard(
+ $lng->txt("blog_latest_posting"),
+ $ctrl->getLinkTargetByClass("ilblogpostinggui", $cmd)
+ );
+ } else {
+ $mb = $f->button()->standard($lng->txt("blog_latest_posting"), "#")->withUnavailableAction();
+ }
+
+ $prev_posting = $this->getPreviousPosting($a_items);
+ if ($prev_posting != "") {
+ $ctrl->setParameterByClass("ilblogpostinggui", "blpg", $prev_posting);
+ $pb = $f->button()->standard(
+ $lng->txt("previous"),
+ $ctrl->getLinkTargetByClass("ilblogpostinggui", $cmd)
+ );
+ } else {
+ $pb = $f->button()->standard($lng->txt("previous"), "#")->withUnavailableAction();
+ }
+
+ $next_posting = $this->getNextPosting($a_items);
+ if ($next_posting != "") {
+ $ctrl->setParameterByClass("ilblogpostinggui", "blpg", $next_posting);
+ $nb = $f->button()->standard(
+ $lng->txt("next"),
+ $ctrl->getLinkTargetByClass("ilblogpostinggui", $cmd)
+ );
+ } else {
+ $nb = $f->button()->standard($lng->txt("next"), "#")->withUnavailableAction();
+ }
+ $ctrl->setParameter($this, "blpg", $this->blpg);
+ $vc = $f->viewControl()->section($pb, $mb, $nb);
+ $toolbar->addComponent($vc);
+ } else { // month view
+ include_once "Services/Calendar/classes/class.ilCalendarUtil.php";
+
+ $latest_month = $this->getLatestMonth($a_items);
+ if ($latest_month != "" && $this->month != $latest_month) {
+ $ctrl->setParameter($this, "bmn", $latest_month);
+ $mb = $f->button()->standard(
+ $lng->txt("blog_latest_posting"),
+ $ctrl->getLinkTarget($this, "preview")
+ );
+ } else {
+ $mb = $f->button()->standard($lng->txt("blog_latest_posting"), "#")->withUnavailableAction();
+ }
+
+ $prev_month = $this->getPreviousMonth($a_items);
+ if ($prev_month != "") {
+ $ctrl->setParameter($this, "bmn", $prev_month);
+ $pb = $f->button()->standard($lng->txt("previous"), $ctrl->getLinkTarget($this, "preview"));
+ } else {
+ $pb = $f->button()->standard($lng->txt("previous"), "#")->withUnavailableAction();
+ }
+
+ $next_month = $this->getNextMonth($a_items);
+ if ($next_month != "") {
+ $ctrl->setParameter($this, "bmn", $next_month);
+ $nb = $f->button()->standard($lng->txt("next"), $ctrl->getLinkTarget($this, "preview"));
+ } else {
+ $nb = $f->button()->standard($lng->txt("next"), "#")->withUnavailableAction();
+ }
+ $ctrl->setParameter($this, "bmn", $this->month);
+ $vc = $f->viewControl()->section($pb, $mb, $nb);
+ $toolbar->addComponent($vc);
+ }
+ }
+
+ /**
+ * Get next month
+ *
+ * @param array $a_items item array
+ * @return string
+ */
+ public function getNextMonth($a_items)
+ {
+ reset($a_items);
+ $found = "";
+ foreach ($a_items as $month => $items) {
+ if ($month > $this->month) {
+ $found = $month;
+ }
+ }
+ return $found;
+ }
+
+ /**
+ * Get next month
+ *
+ * @param array $a_items item array
+ * @return string
+ */
+ public function getPreviousMonth($a_items)
+ {
+ reset($a_items);
+ $found = "";
+ foreach ($a_items as $month => $items) {
+ if ($month < $this->month && $found == "") {
+ $found = $month;
+ }
+ }
+ return $found;
+ }
+
+ /**
+ * Get next month
+ *
+ * @param array $a_items item array
+ * @return string
+ */
+ public function getLatestMonth($a_items)
+ {
+ reset($a_items);
+ return key($a_items);
+ }
+
+ /**
+ * Get next posting
+ *
+ * @param array $a_items item array
+ * @return int page id
+ */
+ public function getNextPosting($a_items)
+ {
+ reset($a_items);
+ $found = "";
+ $next_blpg = 0;
+ foreach ($a_items as $month => $items) {
+ foreach ($items as $item) {
+ if ($item["id"] == $this->blpg) {
+ $found = true;
+ }
+ if (!$found) {
+ $next_blpg = $item["id"];
+ }
+ }
+ }
+ return $next_blpg;
+ }
+
+ /**
+ * Get previous posting
+ *
+ * @param array $a_items item array
+ * @return int page id
+ */
+ public function getPreviousPosting($a_items)
+ {
+ reset($a_items);
+ $found = "";
+ $prev_blpg = 0;
+ foreach ($a_items as $month => $items) {
+ foreach ($items as $item) {
+ if ($found && $prev_blpg == "") {
+ $prev_blpg = $item["id"];
+ }
+ if ($item["id"] == $this->blpg) {
+ $found = true;
+ }
+ }
+ }
+ return $prev_blpg;
+ }
+
+ /**
+ * Get previous posting
+ *
+ * @param array $a_items item array
+ * @return int page id
+ */
+ public function getLatestPosting($a_items)
+ {
+ reset($a_items);
+ $month = current($a_items);
+ if (is_array($month)) {
+ return current($month)["id"];
+ }
+ return false;
+ }
+
+ /**
+ * Build navigation blocks
+ *
+ * @param array $a_items
+ * @param string $a_list_cmd
+ * @param string $a_posting_cmd
+ * @param bool $a_link_template
+ * @param bool $a_show_inactive
+ * @param int $a_blpg blog page id
+ * @return string
+ */
+ public function renderNavigation(array $a_items, $a_list_cmd = "render", $a_posting_cmd = "preview", $a_link_template = null, $a_show_inactive = false, $a_blpg = 0)
+ {
+ $ilCtrl = $this->ctrl;
+ $ilSetting = $this->settings;
+
+ $blpg = ($a_blpg > 0)
+ ? $a_blpg
+ : $this->blpg;
+
+ if ($this->object->getOrder()) {
+ $order = array_flip($this->object->getOrder());
+ } else {
+ $order = array(
+ "navigation" => 0
+ ,"keywords" => 2
+ ,"authors" => 1
+ );
+ }
+
+ $wtpl = new ilTemplate("tpl.blog_list_navigation.html", true, true, "Modules/Blog");
+
+ $blocks = array();
+
+ // by date
+ if (sizeof($a_items)) {
+ $blocks[$order["navigation"]] = array(
+ $this->lng->txt("blog_navigation"),
+ $this->renderNavigationByDate($a_items, $a_list_cmd, $a_posting_cmd, $a_link_template, $a_show_inactive, $a_blpg)
+ );
+ }
+
+ if ($this->object->hasKeywords()) {
+ // keywords
+ $may_edit_keywords = ($blpg > 0 &&
+ $this->mayEditPosting($blpg) &&
+ $a_list_cmd != "preview" &&
+ $a_list_cmd != "gethtml" &&
+ !$a_link_template);
+ $keywords = $this->renderNavigationByKeywords($a_list_cmd, $a_show_inactive, $a_link_template, $a_blpg);
+ if ($keywords || $may_edit_keywords) {
+ if (!$keywords) {
+ $keywords = $this->lng->txt("blog_no_keywords");
+ }
+ $cmd = null;
+ $blocks[$order["keywords"]] = array(
+ $this->lng->txt("blog_keywords"),
+ $keywords,
+ $cmd
+ ? array($cmd, $this->lng->txt("blog_edit_keywords"))
+ : null
+ );
+ }
+ }
+
+ // is not part of (html) export
+ if (!$a_link_template) {
+ // authors
+ if ($this->id_type == self::REPOSITORY_NODE_ID &&
+ $this->object->hasAuthors()) {
+ $authors = $this->renderNavigationByAuthors($a_items, $a_list_cmd, $a_show_inactive);
+ if ($authors) {
+ $blocks[$order["authors"]] = array($this->lng->txt("blog_authors"), $authors);
+ }
+ }
+
+ // rss
+ if ($this->object->hasRSS() &&
+ $ilSetting->get('enable_global_profiles') &&
+ $a_list_cmd == "preview") {
+ // #10827
+ $blog_id = $this->node_id;
+ if ($this->id_type != self::WORKSPACE_NODE_ID) {
+ $blog_id .= "_cll";
+ }
+ $url = ILIAS_HTTP_PATH . "/feed.php?blog_id=" . $blog_id .
+ "&client_id=" . rawurlencode(CLIENT_ID);
+
+ include_once("./Services/News/classes/class.ilRSSButtonGUI.php");
+ $wtpl->setVariable("RSS_BUTTON", ilRSSButtonGUI::get(ilRSSButtonGUI::ICON_RSS, $url));
+ }
+ }
+
+ if (sizeof($blocks)) {
+ include_once "Services/UIComponent/Panel/classes/class.ilPanelGUI.php";
+
+ ksort($blocks);
+ foreach ($blocks as $block) {
+ $panel = ilPanelGUI::getInstance();
+ $panel->setPanelStyle(ilPanelGUI::PANEL_STYLE_SECONDARY);
+ $panel->setHeadingStyle(ilPanelGUI::HEADING_STYLE_BLOCK);
+ $panel->setHeading($block[0]);
+ $panel->setBody($block[1]);
+
+ if (isset($block[2]) && is_array($block[2])) {
+ $panel->setFooter('' . $block[2][1] . '');
+ }
+
+ $wtpl->setCurrentBlock("block_bl");
+ $wtpl->setVariable("BLOCK", $panel->getHTML());
+ $wtpl->parseCurrentBlock();
+ }
+ }
+
+ return $wtpl->get();
+ }
+
+ /**
+ * Get keywords for single posting or complete blog
+ *
+ * @param bool $a_show_inactive
+ * @param int $a_posting_id
+ * @return array
+ */
+ public function getKeywords($a_show_inactive, $a_posting_id = null)
+ {
+ $keywords = array();
+ include_once("./Modules/Blog/classes/class.ilBlogPosting.php");
+ if ($a_posting_id) {
+ foreach (ilBlogPosting::getKeywords($this->obj_id, $a_posting_id) as $keyword) {
+ $keywords[$keyword]++;
+ }
+ } else {
+ foreach ($this->items as $month => $items) {
+ foreach ($items as $item) {
+ if ($a_show_inactive || ilBlogPosting::_lookupActive($item["id"], "blp")) {
+ foreach (ilBlogPosting::getKeywords($this->obj_id, $item["id"]) as $keyword) {
+ $keywords[$keyword]++;
+ }
+ }
+ }
+ }
+ }
+
+ // #15881
+ $tmp = array();
+ foreach ($keywords as $keyword => $counter) {
+ $tmp[] = array("keyword"=>$keyword, "counter"=>$counter);
+ }
+ $tmp = ilUtil::sortArray($tmp, "keyword", "ASC");
+
+ $keywords = array();
+ foreach ($tmp as $item) {
+ $keywords[$item["keyword"]] = $item["counter"];
+ }
+ return $keywords;
+ }
+
+ /**
+ * Build export file
+ *
+ * @return string
+ */
+ public function buildExportFile()
+ {
+ // create export file
+ include_once("./Services/Export/classes/class.ilExport.php");
+ ilExport::_createExportDirectory($this->object->getId(), "html", "blog");
+ $exp_dir = ilExport::_getExportDirectory($this->object->getId(), "html", "blog");
+
+ $subdir = $this->object->getType() . "_" . $this->object->getId();
+ $export_dir = $exp_dir . "/" . $subdir;
+
+ // initialize temporary target directory
+ ilUtil::delDir($export_dir);
+ ilUtil::makeDir($export_dir);
+
+ // system style html exporter
+ include_once("./Services/Style/System/classes/class.ilSystemStyleHTMLExport.php");
+ $this->sys_style_html_export = new ilSystemStyleHTMLExport($export_dir);
+ $this->sys_style_html_export->addImage("icon_blog.svg");
+ $this->sys_style_html_export->export();
+
+ // init co page html exporter
+ include_once("./Services/COPage/classes/class.ilCOPageHTMLExport.php");
+ $this->co_page_html_export = new ilCOPageHTMLExport($export_dir);
+ $this->co_page_html_export->setContentStyleId($this->object->getStyleSheetId());
+ $this->co_page_html_export->createDirectories();
+ $this->co_page_html_export->exportStyles();
+ $this->co_page_html_export->exportSupportScripts();
+
+ // banner / profile picture
+ $blga_set = new ilSetting("blga");
+ if ($blga_set->get("banner")) {
+ $banner = $this->object->getImageFullPath();
+ if ($banner) {
+ copy($banner, $export_dir . "/" . basename($banner));
+ }
+ }
+ $ppic = ilObjUser::_getPersonalPicturePath($this->object->getOwner(), "xsmall", true, true);
+ if ($ppic) {
+ $ppic = array_shift(explode("?", $ppic));
+ copy($ppic, $export_dir . "/" . basename($ppic));
+ }
+
+ // export pages
+ $this->exportHTMLPages($export_dir);
+
+ // zip everything
+ if (true) {
+ // zip it all
+ $date = time();
+ $zip_file = ilExport::_getExportDirectory($this->object->getId(), "html", "blog") .
+ "/" . $date . "__" . IL_INST_ID . "__" .
+ $this->object->getType() . "_" . $this->object->getId() . ".zip";
+ ilUtil::zip($export_dir, $zip_file);
+ ilUtil::delDir($export_dir);
+ }
+
+ return $zip_file;
+ }
+
+ /**
+ * Export all pages
+ *
+ * @param string $a_target_directory
+ * @param string $a_link_template (embedded)
+ * @param array $a_tpl_callback (embedded)
+ * @param object $a_co_page_html_export (embedded)
+ * @param string $a_index_name (embedded)
+ */
+ public function exportHTMLPages($a_target_directory, $a_link_template = null, $a_tpl_callback = null, $a_co_page_html_export = null, $a_index_name = "index.html")
+ {
+ require_once('Services/MathJax/classes/class.ilMathJax.php');
+ ilMathJax::getInstance()->init(ilMathJax::PURPOSE_EXPORT);
+
+ if (!$a_link_template) {
+ $a_link_template = "bl{TYPE}_{ID}.html";
+ }
+
+ if ($a_co_page_html_export) {
+ $this->co_page_html_export = $a_co_page_html_export;
+ }
+
+
+ // lists
+
+ // global nav
+ $nav = $this->renderNavigation($this->items, "", "", $a_link_template);
+
+ // month list
+ $has_index = false;
+ foreach (array_keys($this->items) as $month) {
+ $list = $this->renderList($this->items[$month], "render", $a_link_template, false, $a_target_directory);
+
+ if (!$list) {
+ continue;
+ }
+
+ if (!$a_tpl_callback) {
+ $tpl = $this->buildExportTemplate();
+ } else {
+ $tpl = call_user_func($a_tpl_callback);
+ }
+
+ $file = $this->buildExportLink($a_link_template, "list", $month);
+ $file = $this->writeExportFile(
+ $a_target_directory,
+ $file,
+ $tpl,
+ $list,
+ $nav
+ );
+
+ if (!$has_index) {
+ copy($file, $a_target_directory . "/" . $a_index_name);
+ $has_index = true;
+ }
+ }
+
+ // keywords
+ foreach (array_keys($this->getKeywords(false)) as $keyword) {
+ $this->keyword = $keyword;
+ $list_items = $this->filterItemsByKeyword($this->items, $keyword);
+ $list = $this->renderList($list_items, "render", $a_link_template, false, $a_target_directory);
+
+ if (!$list) {
+ continue;
+ }
+
+ if (!$a_tpl_callback) {
+ $tpl = $this->buildExportTemplate();
+ } else {
+ $tpl = call_user_func($a_tpl_callback);
+ }
+
+ $file = $this->buildExportLink($a_link_template, "keyword", $keyword);
+ $file = $this->writeExportFile(
+ $a_target_directory,
+ $file,
+ $tpl,
+ $list,
+ $nav
+ );
+ }
+
+
+ // single postings
+
+ include_once("./Services/COPage/classes/class.ilPageContentUsage.php");
+ include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php");
+ $pages = ilBlogPosting::getAllPostings($this->object->getId(), 0);
+ foreach ($pages as $page) {
+ if (ilBlogPosting::_exists("blp", $page["id"])) {
+ include_once("./Modules/Blog/classes/class.ilBlogPostingGUI.php");
+ $blp_gui = new ilBlogPostingGUI(0, null, $page["id"]);
+ $blp_gui->setOutputMode("offline");
+ $blp_gui->setFullscreenLink("fullscreen.html"); // #12930 - see page.xsl
+ $blp_gui->add_date = true;
+ $page_content = $blp_gui->showPage();
+
+ $back = $this->buildExportLink(
+ $a_link_template,
+ "list",
+ substr($page["created"]->get(IL_CAL_DATE), 0, 7)
+ );
+
+ $file = $this->buildExportLink($a_link_template, "posting", $page["id"]);
+
+ if (!$a_tpl_callback) {
+ $tpl = $this->buildExportTemplate();
+ } else {
+ $tpl = call_user_func($a_tpl_callback);
+ }
+
+ // posting nav
+ $nav = $this->renderNavigation(
+ $this->items,
+ "",
+ "",
+ $a_link_template,
+ false,
+ $page["id"]
+ );
+
+ $this->writeExportFile(
+ $a_target_directory,
+ $file,
+ $tpl,
+ $page_content,
+ $nav,
+ $back
+ );
+
+ $this->co_page_html_export->collectPageElements("blp:pg", $page["id"]);
+ }
+ }
+ $this->co_page_html_export->exportPageElements();
+ }
+
+ /**
+ * Build static export link
+ *
+ * @param string $a_template
+ * @param string $a_type
+ * @param mixed $a_id
+ * @return string
+ */
+ protected function buildExportLink($a_template, $a_type, $a_id)
+ {
+ switch ($a_type) {
+ case "list":
+ $a_type = "m";
+ break;
+ break;
+
+ case "keyword":
+ if (!self::$keyword_export_map) {
+ self::$keyword_export_map = array_flip(array_keys($this->getKeywords(false)));
+ }
+ $a_id = self::$keyword_export_map[$a_id];
+ $a_type = "k";
+ break;
+
+ default:
+ $a_type = "p";
+ break;
+ }
+
+ $link = str_replace("{TYPE}", $a_type, $a_template);
+ return str_replace("{ID}", $a_id, $link);
+ }
+
+ /**
+ * Build export "frame"
+ *
+ * @param type $a_back_url
+ * @return ilTemplate
+ */
+ protected function buildExportTemplate($a_back_url = "")
+ {
+ $ilTabs = $this->tabs;
+ $lng = $this->lng;
+
+ $tpl = $this->co_page_html_export->getPreparedMainTemplate();
+
+ $tpl->getStandardTemplate();
+
+ $ilTabs->clearTargets();
+ if ($a_back_url) {
+ $ilTabs->setBackTarget($lng->txt("back"), $a_back_url);
+ }
+
+ $this->renderFullscreenHeader($tpl, $this->object->getOwner(), true);
+
+ return $tpl;
+ }
+
+ /**
+ * Write HTML to file
+ *
+ * @param type $a_target_directory
+ * @param type $a_file
+ * @param type $a_tpl
+ * @param type $a_content
+ * @param type $a_right_content
+ * @return string
+ */
+ protected function writeExportFile($a_target_directory, $a_file, $a_tpl, $a_content, $a_right_content = null, $a_back = null)
+ {
+ $file = $a_target_directory . "/" . $a_file;
+ // return if file is already existing
+ if (@is_file($file)) {
+ return;
+ }
+
+ // export template: page content
+ $ep_tpl = new ilTemplate(
+ "tpl.export_page.html",
+ true,
+ true,
+ "Modules/Blog"
+ );
+ if ($a_back) {
+ $ep_tpl->setVariable("PAGE_CONTENT", $a_content);
+ } else {
+ $ep_tpl->setVariable("LIST", $a_content);
+ }
+ unset($a_content);
+ $a_tpl->setContent($ep_tpl->get());
+ unset($ep_tpl);
+
+ // template: right content
+ if ($a_right_content) {
+ $a_tpl->setRightContent($a_right_content);
+ unset($a_right_content);
+ }
+
+ $content = $a_tpl->get(
+ "DEFAULT",
+ false,
+ false,
+ false,
+ true,
+ true,
+ true
+ );
+
+ // open file
+ if (!file_put_contents($file, $content)) {
+ die("Error: Could not open \"" . $file . "\" for writing" .
+ " in " . __FILE__ . " on line " . __LINE__ . "
");
+ }
+
+ // set file permissions
+ chmod($file, 0770);
+
+ return $file;
+ }
+
+ public function getNotesSubId()
+ {
+ return $this->blpg;
+ }
+
+ public function disableNotes($a_value = false)
+ {
+ $this->disable_notes = (bool) $a_value;
+ }
+
+ protected function addHeaderActionForCommand($a_cmd)
+ {
+ $ilUser = $this->user;
+ $ilCtrl = $this->ctrl;
+
+ // preview?
+ if ($a_cmd == "preview" || $a_cmd == "previewFullscreen" || $this->prvm) {
+ // notification
+ if ($ilUser->getId() != ANONYMOUS_USER_ID) {
+ if (!$this->prvm) {
+ $ilCtrl->setParameter($this, "prvm", "fsc");
+ }
+ $this->insertHeaderAction($this->initHeaderAction(null, null, true));
+ if (!$this->prvm) {
+ $ilCtrl->setParameter($this, "prvm", "");
+ }
+ }
+ } else {
+ return parent::addHeaderAction();
+ }
+ }
+
+ protected function initHeaderAction($sub_type = null, $sub_id = null, $a_is_preview = false)
+ {
+ $ilUser = $this->user;
+ $ilCtrl = $this->ctrl;
+
+ if (!$this->obj_id) {
+ return false;
+ }
+
+ $sub_type = $sub_id = null;
+ if ($this->blpg > 0) {
+ $sub_type = "blp";
+ $sub_id = $this->blpg;
+ }
+
+ $lg = parent::initHeaderAction($sub_type, $sub_id);
+
+ if ($a_is_preview) {
+ $lg->enableComments(false);
+ $lg->enableNotes(false);
+ $lg->enableTags(false);
+
+ include_once "./Services/Notification/classes/class.ilNotification.php";
+ if (ilNotification::hasNotification(ilNotification::TYPE_BLOG, $ilUser->getId(), $this->obj_id)) {
+ $ilCtrl->setParameter($this, "ntf", 1);
+ $link = $ilCtrl->getLinkTarget($this, "setNotification");
+ $ilCtrl->setParameter($this, "ntf", "");
+ if (ilNotification::hasOptOut($this->obj_id)) {
+ $lg->addCustomCommand($link, "blog_notification_toggle_off");
+ }
+
+ $lg->addHeaderIcon(
+ "not_icon",
+ ilUtil::getImagePath("notification_on.svg"),
+ $this->lng->txt("blog_notification_activated")
+ );
+ } else {
+ $ilCtrl->setParameter($this, "ntf", 2);
+ $link = $ilCtrl->getLinkTarget($this, "setNotification");
+ $ilCtrl->setParameter($this, "ntf", "");
+ $lg->addCustomCommand($link, "blog_notification_toggle_on");
+
+ $lg->addHeaderIcon(
+ "not_icon",
+ ilUtil::getImagePath("notification_off.svg"),
+ $this->lng->txt("blog_notification_deactivated")
+ );
+ }
+
+ // #11758
+ if ($this->mayContribute()) {
+ $ilCtrl->setParameter($this, "prvm", "");
+
+ $ilCtrl->setParameter($this, "bmn", "");
+ $ilCtrl->setParameter($this, "blpg", "");
+ $link = $ilCtrl->getLinkTarget($this, "");
+ $ilCtrl->setParameter($this, "blpg", $sub_id);
+ $ilCtrl->setParameter($this, "bmn", $this->month);
+ $lg->addCustomCommand($link, "blog_edit"); // #11868
+
+ if ($sub_id && $this->mayEditPosting($sub_id)) {
+ $link = $ilCtrl->getLinkTargetByClass("ilblogpostinggui", "edit");
+ $lg->addCustomCommand($link, "blog_edit_posting");
+ }
+
+ $ilCtrl->setParameter($this, "prvm", "fsc");
+ }
+
+ $ilCtrl->setParameter($this, "ntf", "");
+ }
+
+ return $lg;
+ }
+
+ protected function setNotification()
+ {
+ $ilUser = $this->user;
+ $ilCtrl = $this->ctrl;
+
+ include_once "./Services/Notification/classes/class.ilNotification.php";
+ switch ($this->ntf) {
+ case 1:
+ ilNotification::setNotification(ilNotification::TYPE_BLOG, $ilUser->getId(), $this->obj_id, false);
+ break;
+
+ case 2:
+ ilNotification::setNotification(ilNotification::TYPE_BLOG, $ilUser->getId(), $this->obj_id, true);
+ break;
+ }
+
+ $ilCtrl->redirect($this, "preview");
+ }
+
+ /**
+ * Get title for blog posting (used in ilNotesGUI)
+ *
+ * @param int $a_blog_id
+ * @param int $a_posting_id
+ * @return string
+ */
+ public static function lookupSubObjectTitle($a_blog_id, $a_posting_id)
+ {
+ // page might be deleted, so setting halt on errors to false
+ include_once "Modules/Blog/classes/class.ilBlogPosting.php";
+ $post = new ilBlogPosting($a_posting_id);
+ if ($post->getBlogId() == $a_blog_id) {
+ return $post->getTitle();
+ }
+ }
+
+ /**
+ * Filter inactive items from items list
+ *
+ * @return array
+ */
+ protected function filterInactivePostings()
+ {
+ foreach ($this->items as $month => $postings) {
+ foreach ($postings as $id => $item) {
+ if (!ilBlogPosting::_lookupActive($id, "blp")) {
+ unset($this->items[$month][$id]);
+ } elseif ($this->object->hasApproval() && !$item["approved"]) {
+ unset($this->items[$month][$id]);
+ }
+ }
+ if (!sizeof($this->items[$month])) {
+ unset($this->items[$month]);
+ }
+ }
+
+ if ($this->items && !isset($this->items[$this->month])) {
+ $this->month = array_shift(array_keys($this->items));
+ }
+ }
+
+ protected function filterItemsByKeyWord(array $a_items, $a_keyword)
+ {
+ $res = array();
+ include_once("./Modules/Blog/classes/class.ilBlogPosting.php");
+ foreach ($a_items as $month => $items) {
+ foreach ($items as $item) {
+ if (in_array(
+ $a_keyword,
+ ilBlogPosting::getKeywords($this->obj_id, $item["id"])
+ )) {
+ $res[] = $item;
+ }
+ }
+ }
+ return $res;
+ }
+
+ /**
+ * Check if user has admin access (approve, may edit & deactivate all postings)
+ *
+ * @return bool
+ */
+ protected function isAdmin()
+ {
+ return ($this->checkPermissionBool("redact") ||
+ $this->checkPermissionBool("write"));
+ }
+
+ /**
+ * Check if user may edit posting
+ *
+ * @param int $a_posting_id
+ * @param int $a_author_id
+ * @return boolean
+ */
+ protected function mayEditPosting($a_posting_id, $a_author_id = null)
+ {
+ $ilUser = $this->user;
+
+ // single author blog (owner) in personal workspace
+ if ($this->id_type == self::WORKSPACE_NODE_ID) {
+ return $this->checkPermissionBool("write");
+ }
+
+ // repository blogs
+
+ // redact allows to edit all postings
+ if ($this->checkPermissionBool("redact")) {
+ return true;
+ }
+
+ // contribute gives access to own postings
+ if ($this->checkPermissionBool("contribute")) {
+ // check owner of posting
+ if (!$a_author_id) {
+ include_once "Modules/Blog/classes/class.ilBlogPosting.php";
+ $post = new ilBlogPosting($a_posting_id);
+ $a_author_id = $post->getAuthor();
+ }
+ if ($ilUser->getId() == $a_author_id) {
+ return true;
+ } else {
+ return false;
+ }
+
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Check if user may contribute at all
+ *
+ * @return boolean
+ */
+ protected function mayContribute()
+ {
+ // single author blog (owner) in personal workspace
+ if ($this->id_type == self::WORKSPACE_NODE_ID) {
+ return $this->checkPermissionBool("write");
+ }
+
+ return ($this->checkPermissionBool("redact") ||
+ $this->checkPermissionBool("contribute"));
+ }
+
+ public function addLocatorItems()
+ {
+ $ilLocator = $this->locator;
+
+ if (is_object($this->object)) {
+ $ilLocator->addItem($this->object->getTitle(), $this->ctrl->getLinkTarget($this, ""), "", $this->node_id);
+ }
+ }
+
+ public function approve()
+ {
+ if ($this->isAdmin() && $this->apid > 0) {
+ include_once "Modules/Blog/classes/class.ilBlogPosting.php";
+ $post = new ilBlogPosting($this->apid);
+ $post->setApproved(true);
+ $post->setBlogNodeId($this->node_id, ($this->id_type == self::WORKSPACE_NODE_ID));
+ $post->update(true, false, true, "new"); // #13434
+
+ ilUtil::sendSuccess($this->lng->txt("settings_saved"), true);
+ }
+
+ $this->ctrl->redirect($this, "render");
+ }
+
+
+ //
+ // contributors
+ //
+
+ public function contributors()
+ {
+ $ilTabs = $this->tabs;
+ $ilToolbar = $this->toolbar;
+ $ilCtrl = $this->ctrl;
+ $lng = $this->lng;
+ $tpl = $this->tpl;
+
+ if (!$this->checkPermissionBool("write")) {
+ return;
+ }
+
+ $ilTabs->activateTab("contributors");
+
+ $local_roles = $this->object->getAllLocalRoles($this->node_id);
+
+ // add member
+ include_once './Services/Search/classes/class.ilRepositorySearchGUI.php';
+ ilRepositorySearchGUI::fillAutoCompleteToolbar(
+ $this,
+ $ilToolbar,
+ array(
+ 'auto_complete_name' => $lng->txt('user'),
+ 'submit_name' => $lng->txt('add'),
+ 'add_search' => true,
+ 'add_from_container' => $this->node_id,
+ 'user_type' => $local_roles
+ ),
+ true
+ );
+
+ $other_roles = $this->object->getRolesWithContributeOrRedact($this->node_id);
+ if ($other_roles) {
+ ilUtil::sendInfo(sprintf($lng->txt("blog_contribute_other_roles"), implode(", ", $other_roles)));
+ }
+
+ include_once "Modules/Blog/classes/class.ilContributorTableGUI.php";
+ $tbl = new ilContributorTableGUI($this, "contributors", $this->object->getAllLocalRoles($this->node_id));
+
+ $tpl->setContent($tbl->getHTML());
+ }
+
+ /**
+ * Autocomplete submit
+ */
+ public function addUserFromAutoComplete()
+ {
+ $lng = $this->lng;
+
+ $user_login = ilUtil::stripSlashes($_POST['user_login']);
+ $user_type = ilUtil::stripSlashes($_POST["user_type"]);
+
+ if (!strlen(trim($user_login))) {
+ ilUtil::sendFailure($lng->txt('msg_no_search_string'));
+ return $this->contributors();
+ }
+ $users = explode(',', $user_login);
+
+ $user_ids = array();
+ foreach ($users as $user) {
+ $user_id = ilObjUser::_lookupId($user);
+
+ if (!$user_id) {
+ ilUtil::sendFailure($lng->txt('user_not_known'));
+ return $this->contributors();
+ }
+
+ $user_ids[] = $user_id;
+ }
+
+ return $this->addContributor($user_ids, $user_type);
+ }
+
+ /**
+ * Centralized method to add contributors
+ *
+ * @param array $a_user_ids
+ */
+ public function addContributor($a_user_ids = array(), $a_user_type = null)
+ {
+ $ilCtrl = $this->ctrl;
+ $lng = $this->lng;
+ $rbacreview = $this->rbacreview;
+ $rbacadmin = $this->rbacadmin;
+
+ if (!$this->checkPermissionBool("write")) {
+ return;
+ }
+
+ if (!count($a_user_ids) || !$a_user_type) {
+ ilUtil::sendFailure($lng->txt("no_checkbox"));
+ return $this->contributors();
+ }
+
+ // get contributor role
+ $local_roles = array_keys($this->object->getAllLocalRoles($this->node_id));
+ if (!in_array($a_user_type, $local_roles)) {
+ ilUtil::sendFailure($lng->txt("missing_perm"));
+ return $this->contributors();
+ }
+
+ foreach ($a_user_ids as $user_id) {
+ if (!$rbacreview->isAssigned($user_id, $a_user_type)) {
+ $rbacadmin->assignUser($a_user_type, $user_id);
+ }
+ }
+
+ ilUtil::sendSuccess($lng->txt("settings_saved"), true);
+ $ilCtrl->redirect($this, "contributors");
+ }
+
+ /**
+ * Used in ilContributorTableGUI
+ */
+ public function confirmRemoveContributor()
+ {
+ $ids = ilUtil::stripSlashesRecursive($_POST["id"]);
+
+ if (!is_array($ids)) {
+ ilUtil::sendFailure($this->lng->txt("select_one"), true);
+ $this->ctrl->redirect($this, "contributors");
+ }
+
+ include_once './Services/Utilities/classes/class.ilConfirmationGUI.php';
+ $confirm = new ilConfirmationGUI();
+ $confirm->setHeaderText($this->lng->txt('blog_confirm_delete_contributors'));
+ $confirm->setFormAction($this->ctrl->getFormAction($this, 'removeContributor'));
+ $confirm->setConfirm($this->lng->txt('delete'), 'removeContributor');
+ $confirm->setCancel($this->lng->txt('cancel'), 'contributors');
+
+ include_once 'Services/User/classes/class.ilUserUtil.php';
+
+ foreach ($ids as $user_id) {
+ $confirm->addItem(
+ 'id[]',
+ $user_id,
+ ilUserUtil::getNamePresentation($user_id, false, false, "", true)
+ );
+ }
+
+ $this->tpl->setContent($confirm->getHTML());
+ }
+
+ /**
+ * Used in ilContributorTableGUI
+ */
+ public function removeContributor()
+ {
+ $ilCtrl = $this->ctrl;
+ $lng = $this->lng;
+ $rbacadmin = $this->rbacadmin;
+
+ $ids = ilUtil::stripSlashesRecursive($_POST["id"]);
+
+ if (!is_array($ids)) {
+ ilUtil::sendFailure($lng->txt("select_one"), true);
+ $ilCtrl->redirect($this, "contributors");
+ }
+
+ // get contributor role
+ $local_roles = array_keys($this->object->getAllLocalRoles($this->node_id));
+ if (!$local_roles) {
+ ilUtil::sendFailure($lng->txt("missing_perm"));
+ return $this->contributors();
+ }
+
+ foreach ($ids as $user_id) {
+ foreach ($local_roles as $role_id) {
+ $rbacadmin->deassignUser($role_id, $user_id);
+ }
+ }
+
+ ilUtil::sendSuccess($lng->txt("settings_saved"), true);
+ $this->ctrl->redirect($this, "contributors");
+ }
+
+ /**
+ * @see ilDesktopItemHandling::addToDesk()
+ */
+ public function addToDeskObject()
+ {
+ $lng = $this->lng;
+
+ include_once './Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php';
+ ilDesktopItemGUI::addToDesktop();
+ ilUtil::sendSuccess($lng->txt("added_to_desktop"));
+ }
+
+ /**
+ * @see ilDesktopItemHandling::removeFromDesk()
+ */
+ public function removeFromDeskObject()
+ {
+ $lng = $this->lng;
+
+ include_once './Services/PersonalDesktop/classes/class.ilDesktopItemGUI.php';
+ ilDesktopItemGUI::removeFromDesktop();
+ ilUtil::sendSuccess($lng->txt("removed_from_desktop"));
+ }
+
+ public function deactivateAdmin()
+ {
+ if ($this->checkPermissionBool("write") && $this->apid > 0) {
+ // ilBlogPostingGUI::deactivatePage()
+ include_once "Modules/Blog/classes/class.ilBlogPosting.php";
+ $post = new ilBlogPosting($this->apid);
+ $post->setApproved(false);
+ $post->setActive(false);
+ $post->update(true, false, false);
+
+ ilUtil::sendSuccess($this->lng->txt("settings_saved"), true);
+ }
+
+ $this->ctrl->redirect($this, "render");
+ }
+
+
+ ////
+ //// Style related functions
+ ////
+
+ public function setContentStyleSheet($a_tpl = null)
+ {
+ $tpl = $this->tpl;
+
+ if ($a_tpl != null) {
+ $ctpl = $a_tpl;
+ } else {
+ $ctpl = $tpl;
+ }
+
+ $ctpl->setCurrentBlock("ContentStyle");
+ $ctpl->setVariable(
+ "LOCATION_CONTENT_STYLESHEET",
+ ilObjStyleSheet::getContentStylePath($this->object->getStyleSheetId())
+ );
+ $ctpl->parseCurrentBlock();
+ }
+
+ public function editStyleProperties()
+ {
+ $this->checkPermission("write");
+
+ $this->tabs_gui->activateTab("settings");
+ $this->setSettingsSubTabs("style");
+
+ $form = $this->initStylePropertiesForm();
+ $this->tpl->setContent($form->getHTML());
+ }
+
+ public function initStylePropertiesForm()
+ {
+ $ilSetting = $this->settings;
+
+ include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php");
+ $this->lng->loadLanguageModule("style");
+
+ include_once("./Services/Form/classes/class.ilPropertyFormGUI.php");
+ $form = new ilPropertyFormGUI();
+
+ $fixed_style = $ilSetting->get("fixed_content_style_id");
+ $style_id = $this->object->getStyleSheetId();
+
+ if ($fixed_style > 0) {
+ $st = new ilNonEditableValueGUI($this->lng->txt("style_current_style"));
+ $st->setValue(ilObject::_lookupTitle($fixed_style) . " (" .
+ $this->lng->txt("global_fixed") . ")");
+ $form->addItem($st);
+ } else {
+ $st_styles = ilObjStyleSheet::_getStandardStyles(
+ true,
+ false,
+ $this->ref_id
+ );
+
+ $st_styles[0] = $this->lng->txt("default");
+ ksort($st_styles);
+
+ if ($style_id > 0) {
+ // individual style
+ if (!ilObjStyleSheet::_lookupStandard($style_id)) {
+ $st = new ilNonEditableValueGUI($this->lng->txt("style_current_style"));
+ $st->setValue(ilObject::_lookupTitle($style_id));
+ $form->addItem($st);
+
+ // delete command
+ $form->addCommandButton("editStyle", $this->lng->txt("style_edit_style"));
+ $form->addCommandButton("deleteStyle", $this->lng->txt("style_delete_style"));
+ }
+ }
+
+ if ($style_id <= 0 || ilObjStyleSheet::_lookupStandard($style_id)) {
+ $style_sel = new ilSelectInputGUI(
+ $this->lng->txt("style_current_style"),
+ "style_id"
+ );
+ $style_sel->setOptions($st_styles);
+ $style_sel->setValue($style_id);
+ $form->addItem($style_sel);
+
+ $form->addCommandButton("saveStyleSettings", $this->lng->txt("save"));
+ $form->addCommandButton("createStyle", $this->lng->txt("sty_create_ind_style"));
+ }
+ }
+
+ $form->setTitle($this->lng->txt("blog_style"));
+ $form->setFormAction($this->ctrl->getFormAction($this));
+
+ return $form;
+ }
+
+ public function createStyle()
+ {
+ $this->ctrl->redirectByClass("ilobjstylesheetgui", "create");
+ }
+
+ public function editStyle()
+ {
+ $this->ctrl->redirectByClass("ilobjstylesheetgui", "edit");
+ }
+
+ public function deleteStyle()
+ {
+ $this->ctrl->redirectByClass("ilobjstylesheetgui", "delete");
+ }
+
+ public function saveStyleSettings()
+ {
+ $ilSetting = $this->settings;
+
+ include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php");
+ if ($ilSetting->get("fixed_content_style_id") <= 0 &&
+ (ilObjStyleSheet::_lookupStandard($this->object->getStyleSheetId())
+ || $this->object->getStyleSheetId() == 0)) {
+ $this->object->setStyleSheetId((int) $_POST["style_id"]);
+ $this->object->update();
+
+ ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true);
+ }
+ $this->ctrl->redirect($this, "editStyleProperties");
+ }
+
+ /**
+ * Deep link
+ *
+ * @param string $a_target
+ */
+ public static function _goto($a_target)
+ {
+ global $DIC;
+
+ $ilCtrl = $DIC->ctrl();
+
+ if (substr($a_target, -3) == "wsp") {
+ $id = explode("_", $a_target);
+
+ $ilCtrl->setTargetScript("ilias.php");
+ $ilCtrl->initBaseClass("ilSharedResourceGUI");
+ $ilCtrl->setParameterByClass("ilSharedResourceGUI", "wsp_id", $id[0]);
+
+ if (sizeof($id) >= 2) {
+ if (is_numeric($id[1])) {
+ $ilCtrl->setParameterByClass("ilSharedResourceGUI", "gtp", $id[1]);
+ } else {
+ $ilCtrl->setParameterByClass("ilSharedResourceGUI", "kwd", $id[1]);
+ }
+ }
+ $ilCtrl->redirectByClass("ilSharedResourceGUI", "");
+ } else {
+ $id = explode("_", $a_target);
+
+ $ilCtrl->setTargetScript("ilias.php");
+ $ilCtrl->initBaseClass("ilRepositoryGUI");
+ $ilCtrl->setParameterByClass("ilRepositoryGUI", "ref_id", $id[0]);
+
+ if (sizeof($id) == 2) {
+ if (is_numeric($id[1])) {
+ $ilCtrl->setParameterByClass("ilRepositoryGUI", "gtp", $id[1]);
+ } else {
+ $ilCtrl->setParameterByClass("ilRepositoryGUI", "kwd", $id[1]);
+ }
+ }
+ $ilCtrl->redirectByClass("ilRepositoryGUI", "preview");
+ }
+ }
}
-
-?>
\ No newline at end of file
diff --git a/Modules/Blog/classes/class.ilObjBlogListGUI.php b/Modules/Blog/classes/class.ilObjBlogListGUI.php
index 0765e1744890fd8840be376e7d50584bda55ef1c..ee75edb5fba1724e6f16f12f8c7de436a1399e7f 100644
--- a/Modules/Blog/classes/class.ilObjBlogListGUI.php
+++ b/Modules/Blog/classes/class.ilObjBlogListGUI.php
@@ -14,45 +14,40 @@ include_once "Services/Object/classes/class.ilObjectListGUI.php";
*/
class ilObjBlogListGUI extends ilObjectListGUI
{
- /**
- * initialisation
- */
- function init()
- {
- $this->copy_enabled = true;
- $this->delete_enabled = true;
- $this->cut_enabled = true;
- $this->subscribe_enabled = true;
- $this->link_enabled = true; // #10498
- $this->info_screen_enabled = true;
- $this->type = "blog";
- $this->gui_class_name = "ilobjbloggui";
+ /**
+ * initialisation
+ */
+ public function init()
+ {
+ $this->copy_enabled = true;
+ $this->delete_enabled = true;
+ $this->cut_enabled = true;
+ $this->subscribe_enabled = true;
+ $this->link_enabled = true; // #10498
+ $this->info_screen_enabled = true;
+ $this->type = "blog";
+ $this->gui_class_name = "ilobjbloggui";
- // general commands array
- include_once('./Modules/Blog/classes/class.ilObjBlogAccess.php');
- $this->commands = ilObjBlogAccess::_getCommands();
- }
-
- public function getCommands()
- {
- $commands = parent::getCommands();
-
- // #10182 - handle edit and contribute
- $permissions = array();
- foreach($commands as $idx => $item)
- {
- if($item["lang_var"] == "edit" && $item["granted"])
- {
- $permissions[$item["permission"]] = $idx;
- }
- }
- if(sizeof($permissions) == 2)
- {
- unset($commands[$permissions["contribute"]]);
- }
-
- return $commands;
- }
+ // general commands array
+ include_once('./Modules/Blog/classes/class.ilObjBlogAccess.php');
+ $this->commands = ilObjBlogAccess::_getCommands();
+ }
+
+ public function getCommands()
+ {
+ $commands = parent::getCommands();
+
+ // #10182 - handle edit and contribute
+ $permissions = array();
+ foreach ($commands as $idx => $item) {
+ if ($item["lang_var"] == "edit" && $item["granted"]) {
+ $permissions[$item["permission"]] = $idx;
+ }
+ }
+ if (sizeof($permissions) == 2) {
+ unset($commands[$permissions["contribute"]]);
+ }
+
+ return $commands;
+ }
}
-
-?>
\ No newline at end of file
diff --git a/Modules/BookingManager/classes/class.ilBookCronNotification.php b/Modules/BookingManager/classes/class.ilBookCronNotification.php
index ba1bb406e7ea5d08d09250a3f2dc07a55ce40003..990b97fbd0fd1c1dcc841a910bfa2a45f83039ea 100644
--- a/Modules/BookingManager/classes/class.ilBookCronNotification.php
+++ b/Modules/BookingManager/classes/class.ilBookCronNotification.php
@@ -1,312 +1,289 @@
-
- * @ingroup ModulesBookingManager
- */
-class ilBookCronNotification extends ilCronJob
-{
- /**
- * @var ilLanguage
- */
- protected $lng;
-
- /**
- * @var ilAccessHandler
- */
- protected $access;
-
- /**
- * @var ilLogger
- */
- protected $book_log;
-
- /**
- * Constructor
- */
- function __construct()
- {
- global $DIC;
-
- $this->lng = $DIC->language();
- if (isset($DIC["ilAccess"]))
- {
- $this->access = $DIC->access();
- }
-
- $this->book_log = ilLoggerFactory::getLogger("book");
-
- }
-
- public function getId()
- {
- return "book_notification";
- }
-
- public function getTitle()
- {
- $lng = $this->lng;
-
- $lng->loadLanguageModule("book");
- return $lng->txt("book_notification");
- }
-
- public function getDescription()
- {
- $lng = $this->lng;
-
- $lng->loadLanguageModule("book");
- return $lng->txt("book_notification_info");
- }
-
- public function getDefaultScheduleType()
- {
- return self::SCHEDULE_TYPE_DAILY;
- }
-
- public function getDefaultScheduleValue()
- {
- return;
- }
-
- public function hasAutoActivation()
- {
- return false;
- }
-
- public function hasFlexibleSchedule()
- {
- return false;
- }
-
- public function run()
- {
- $status = ilCronJobResult::STATUS_NO_ACTION;
-
- $count = $this->sendNotifications();
-
- if ($count > 0)
- {
- $status = ilCronJobResult::STATUS_OK;
- }
-
- $result = new ilCronJobResult();
- $result->setStatus($status);
-
- return $result;
- }
-
- /**
- * Send notifications
- *
- * @param
- * @return int
- */
- protected function sendNotifications()
- {
- $log = $this->book_log;
-
- // get all booking pools with notification setting
-
-
-
- $log->debug("start");
-
-
- $notifications = [];
-
- /*
- * pool id 123 > 2 days, ...
- */
- foreach (ilObjBookingPool::getPoolsWithReminders() as $p)
- {
- // determine reservations from max(next day $last_to_ts) up to "rmd_day" days + 1
- // per pool id
- $next_day_ts = mktime(0, 0, 0, date('n'), date('j') + 1);
- $log->debug("next day ts: ".$next_day_ts);
- $last_reminder_to_ts = $p["last_remind_ts"];
- // for debug purposes
- // $last_reminder_to_ts-= 24*60*60;
- $log->debug("last_reminder ts: ".$last_reminder_to_ts);
- $from_ts = max($next_day_ts, $last_reminder_to_ts);
- $log->debug("from ts: ".$from_ts);
- $to_ts = mktime(0, 0, 0, date('n'), date('j') + $p["reminder_day"] + 1);
- $res = [];
-
- $log->debug("pool id: ".$p["booking_pool_id"].", ".$from_ts."-".$to_ts);
-
- if ($to_ts > $from_ts)
- {
- $res = ilBookingReservation::getListByDate(true, null, [
- "from" => $from_ts,
- "to" => $to_ts
- ], [$p["booking_pool_id"]]);
- }
-
- $log->debug("reservations: ".count($res));
-
-//var_dump($res); exit;
-
- // get subscriber of pool id
- $user_ids = ilNotification::getNotificationsForObject(ilNotification::TYPE_BOOK, $p["booking_pool_id"]);
-
- $log->debug("users: ".count($user_ids));
-
- // group by user, type, pool
- foreach ($res as $r)
- {
-
- // users
- $log->debug("check notification of user id: ".$r["user_id"]);
- if (in_array($r["user_id"], $user_ids))
- {
- if ($this->checkAccess("read", $r["user_id"], $p["booking_pool_id"]))
- {
- $notifications[$r["user_id"]]["personal"][$r["pool_id"]][] = $r;
- }
- }
-
- // admins
- foreach ($user_ids as $uid)
- {
- $log->debug("check write for user id: ".$uid.", pool: ".$p["booking_pool_id"]);
-
- if ($this->checkAccess("write", $uid, $p["booking_pool_id"]))
- {
- $log->debug("got write");
- $notifications[$uid]["admin"][$r["pool_id"]][] = $r;
- }
- }
- }
- ilObjBookingPool::writeLastReminderTimestamp($p["booking_pool_id"], $to_ts);
- }
-
- $log->debug("notifications to users: ".count($notifications));
-
- // send mails
- $this->sendMails($notifications);
-
- return count($notifications);
- }
-
- /**
- * Send mails
- *
- * @param
- */
- protected function sendMails($notifications)
- {
- foreach ($notifications as $uid => $n)
- {
- include_once "./Services/Notification/classes/class.ilSystemNotification.php";
- $ntf = new ilSystemNotification();
- $lng = $ntf->getUserLanguage($uid);
- $lng->loadLanguageModule("book");
-
- $txt = "";
- if (is_array($n["personal"]))
- {
- $txt.= "\n".$lng->txt("book_your_reservations")."\n";
- $txt.= "-----------------------------------------\n";
- foreach ($n["personal"] as $obj_id => $reservs)
- {
- $txt.= ilObject::_lookupTitle($obj_id).":\n";
- foreach ($reservs as $r)
- {
- $txt.= "- ".$r["title"]." (".$r["counter"]."), ".
- ilDatePresentation::formatDate(new ilDate($r["date"], IL_CAL_DATE)).", ".
- $r["slot"]."\n";
- }
- }
- }
-
- if (is_array($n["admin"]))
- {
- $txt.= "\n".$lng->txt("book_reservation_overview")."\n";
- $txt.= "-----------------------------------------\n";
- foreach ($n["admin"] as $obj_id => $reservs)
- {
- $txt.= ilObject::_lookupTitle($obj_id).":\n";
- foreach ($reservs as $r)
- {
- $txt.= "- ".$r["title"]." (".$r["counter"]."), ".$r["user_name"].", ".
- ilDatePresentation::formatDate(new ilDate($r["date"], IL_CAL_DATE)).", ".
- $r["slot"]."\n";
- }
- }
- }
-
- $ntf->setLangModules(array("book"));
- $ntf->setSubjectLangId("book_booking_reminders");
- $ntf->setIntroductionLangId("book_rem_intro");
- $ntf->addAdditionalInfo("", $txt);
- $ntf->setReasonLangId("book_rem_reason");
- $ntf->sendMail(array($uid));
- }
- }
-
-
- /**
- * check access on obj id
- *
- * @param
- * @return
- */
- protected function checkAccess($perm, $uid, $obj_id)
- {
- $access = $this->access;
- foreach (ilObject::_getAllReferences($obj_id) as $ref_id)
- {
- if ($access->checkAccessOfUser($uid, $perm, "", $ref_id))
- {
- return true;
- }
- }
- return false;
- }
-
-
- /**
- * Send user notifications
- *
- * @return int
- */
- protected function sendUserNotifications($res)
- {
- /*
- * Your reservations for tomorrow
- *
- * Pool Title
- * Pool Link
- * - Object (cnt), From - To
- * - ...
- *
- * Reservations for tomorrow
- *
- * Pool Title
- * Pool Link
- * - Object (cnt), From - To
- * - ...
- *
- */
- }
-
- /**
- * Send admin notifications
- *
- * @return int
- */
- protected function sendAdminNotifications($res)
- {
-
- }
-
-}
-
-?>
\ No newline at end of file
+
+ * @ingroup ModulesBookingManager
+ */
+class ilBookCronNotification extends ilCronJob
+{
+ /**
+ * @var ilLanguage
+ */
+ protected $lng;
+
+ /**
+ * @var ilAccessHandler
+ */
+ protected $access;
+
+ /**
+ * @var ilLogger
+ */
+ protected $book_log;
+
+ /**
+ * Constructor
+ */
+ public function __construct()
+ {
+ global $DIC;
+
+ $this->lng = $DIC->language();
+ if (isset($DIC["ilAccess"])) {
+ $this->access = $DIC->access();
+ }
+
+ $this->book_log = ilLoggerFactory::getLogger("book");
+ }
+
+ public function getId()
+ {
+ return "book_notification";
+ }
+
+ public function getTitle()
+ {
+ $lng = $this->lng;
+
+ $lng->loadLanguageModule("book");
+ return $lng->txt("book_notification");
+ }
+
+ public function getDescription()
+ {
+ $lng = $this->lng;
+
+ $lng->loadLanguageModule("book");
+ return $lng->txt("book_notification_info");
+ }
+
+ public function getDefaultScheduleType()
+ {
+ return self::SCHEDULE_TYPE_DAILY;
+ }
+
+ public function getDefaultScheduleValue()
+ {
+ return;
+ }
+
+ public function hasAutoActivation()
+ {
+ return false;
+ }
+
+ public function hasFlexibleSchedule()
+ {
+ return false;
+ }
+
+ public function run()
+ {
+ $status = ilCronJobResult::STATUS_NO_ACTION;
+
+ $count = $this->sendNotifications();
+
+ if ($count > 0) {
+ $status = ilCronJobResult::STATUS_OK;
+ }
+
+ $result = new ilCronJobResult();
+ $result->setStatus($status);
+
+ return $result;
+ }
+
+ /**
+ * Send notifications
+ *
+ * @param
+ * @return int
+ */
+ protected function sendNotifications()
+ {
+ $log = $this->book_log;
+
+ // get all booking pools with notification setting
+
+
+
+ $log->debug("start");
+
+
+ $notifications = [];
+
+ /*
+ * pool id 123 > 2 days, ...
+ */
+ foreach (ilObjBookingPool::getPoolsWithReminders() as $p) {
+ // determine reservations from max(next day $last_to_ts) up to "rmd_day" days + 1
+ // per pool id
+ $next_day_ts = mktime(0, 0, 0, date('n'), date('j') + 1);
+ $log->debug("next day ts: " . $next_day_ts);
+ $last_reminder_to_ts = $p["last_remind_ts"];
+ // for debug purposes
+ // $last_reminder_to_ts-= 24*60*60;
+ $log->debug("last_reminder ts: " . $last_reminder_to_ts);
+ $from_ts = max($next_day_ts, $last_reminder_to_ts);
+ $log->debug("from ts: " . $from_ts);
+ $to_ts = mktime(0, 0, 0, date('n'), date('j') + $p["reminder_day"] + 1);
+ $res = [];
+
+ $log->debug("pool id: " . $p["booking_pool_id"] . ", " . $from_ts . "-" . $to_ts);
+
+ if ($to_ts > $from_ts) {
+ $res = ilBookingReservation::getListByDate(true, null, [
+ "from" => $from_ts,
+ "to" => $to_ts
+ ], [$p["booking_pool_id"]]);
+ }
+
+ $log->debug("reservations: " . count($res));
+
+ //var_dump($res); exit;
+
+ // get subscriber of pool id
+ $user_ids = ilNotification::getNotificationsForObject(ilNotification::TYPE_BOOK, $p["booking_pool_id"]);
+
+ $log->debug("users: " . count($user_ids));
+
+ // group by user, type, pool
+ foreach ($res as $r) {
+
+ // users
+ $log->debug("check notification of user id: " . $r["user_id"]);
+ if (in_array($r["user_id"], $user_ids)) {
+ if ($this->checkAccess("read", $r["user_id"], $p["booking_pool_id"])) {
+ $notifications[$r["user_id"]]["personal"][$r["pool_id"]][] = $r;
+ }
+ }
+
+ // admins
+ foreach ($user_ids as $uid) {
+ $log->debug("check write for user id: " . $uid . ", pool: " . $p["booking_pool_id"]);
+
+ if ($this->checkAccess("write", $uid, $p["booking_pool_id"])) {
+ $log->debug("got write");
+ $notifications[$uid]["admin"][$r["pool_id"]][] = $r;
+ }
+ }
+ }
+ ilObjBookingPool::writeLastReminderTimestamp($p["booking_pool_id"], $to_ts);
+ }
+
+ $log->debug("notifications to users: " . count($notifications));
+
+ // send mails
+ $this->sendMails($notifications);
+
+ return count($notifications);
+ }
+
+ /**
+ * Send mails
+ *
+ * @param
+ */
+ protected function sendMails($notifications)
+ {
+ foreach ($notifications as $uid => $n) {
+ include_once "./Services/Notification/classes/class.ilSystemNotification.php";
+ $ntf = new ilSystemNotification();
+ $lng = $ntf->getUserLanguage($uid);
+ $lng->loadLanguageModule("book");
+
+ $txt = "";
+ if (is_array($n["personal"])) {
+ $txt.= "\n" . $lng->txt("book_your_reservations") . "\n";
+ $txt.= "-----------------------------------------\n";
+ foreach ($n["personal"] as $obj_id => $reservs) {
+ $txt.= ilObject::_lookupTitle($obj_id) . ":\n";
+ foreach ($reservs as $r) {
+ $txt.= "- " . $r["title"] . " (" . $r["counter"] . "), " .
+ ilDatePresentation::formatDate(new ilDate($r["date"], IL_CAL_DATE)) . ", " .
+ $r["slot"] . "\n";
+ }
+ }
+ }
+
+ if (is_array($n["admin"])) {
+ $txt.= "\n" . $lng->txt("book_reservation_overview") . "\n";
+ $txt.= "-----------------------------------------\n";
+ foreach ($n["admin"] as $obj_id => $reservs) {
+ $txt.= ilObject::_lookupTitle($obj_id) . ":\n";
+ foreach ($reservs as $r) {
+ $txt.= "- " . $r["title"] . " (" . $r["counter"] . "), " . $r["user_name"] . ", " .
+ ilDatePresentation::formatDate(new ilDate($r["date"], IL_CAL_DATE)) . ", " .
+ $r["slot"] . "\n";
+ }
+ }
+ }
+
+ $ntf->setLangModules(array("book"));
+ $ntf->setSubjectLangId("book_booking_reminders");
+ $ntf->setIntroductionLangId("book_rem_intro");
+ $ntf->addAdditionalInfo("", $txt);
+ $ntf->setReasonLangId("book_rem_reason");
+ $ntf->sendMail(array($uid));
+ }
+ }
+
+
+ /**
+ * check access on obj id
+ *
+ * @param
+ * @return
+ */
+ protected function checkAccess($perm, $uid, $obj_id)
+ {
+ $access = $this->access;
+ foreach (ilObject::_getAllReferences($obj_id) as $ref_id) {
+ if ($access->checkAccessOfUser($uid, $perm, "", $ref_id)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+
+ /**
+ * Send user notifications
+ *
+ * @return int
+ */
+ protected function sendUserNotifications($res)
+ {
+ /*
+ * Your reservations for tomorrow
+ *
+ * Pool Title
+ * Pool Link
+ * - Object (cnt), From - To
+ * - ...
+ *
+ * Reservations for tomorrow
+ *
+ * Pool Title
+ * Pool Link
+ * - Object (cnt), From - To
+ * - ...
+ *
+ */
+ }
+
+ /**
+ * Send admin notifications
+ *
+ * @return int
+ */
+ protected function sendAdminNotifications($res)
+ {
+ }
+}
diff --git a/Modules/BookingManager/classes/class.ilBookingAssignObjectsTableGUI.php b/Modules/BookingManager/classes/class.ilBookingAssignObjectsTableGUI.php
index a4790f896d5ac13fa6eb27c028be4766aeab19b4..ccb3cc3d0f95866bb22cd382917e563810180402 100644
--- a/Modules/BookingManager/classes/class.ilBookingAssignObjectsTableGUI.php
+++ b/Modules/BookingManager/classes/class.ilBookingAssignObjectsTableGUI.php
@@ -11,161 +11,155 @@
*/
class ilBookingAssignObjectsTableGUI extends ilTable2GUI
{
- /**
- * @var ilAccessHandler
- */
- protected $access;
-
- /**
- * @var ilObjUser
- */
- protected $user;
-
- /**
- * @var int
- */
- protected $ref_id;
-
- /**
- * @var int
- */
- protected $pool_id;
-
- /**
- * @var int
- */
- protected $user_id_to_book;
-
- /**
- * @var ilObjBookingPool
- */
- //protected $bp_object;
-
- /**
- * @var int
- */
- protected $current_bookings; // [int]
-
- /**
- * @var array
- */
- protected $filter; // [array]
-
- /**
- * @var array
- */
- protected $objects; // array
-
- /**
- * @var ilObjBookingPool
- */
- protected $pool;
-
- /**
- * Constructor
- * @param ilBookingParticipantGUI $a_parent_obj
- * @param string $a_parent_cmd
- * @param int $a_ref_id
- * @param int $a_pool_id
- * @param int $a_user_id // user id to be assigned
- */
- function __construct(ilBookingParticipantGUI $a_parent_obj, $a_parent_cmd, $a_ref_id, $a_pool_id)
- {
- global $DIC;
-
- $this->ctrl = $DIC->ctrl();
- $this->lng = $DIC->language();
- $this->user = $DIC->user();
- $this->access = $DIC->access();
- $this->ref_id = $a_ref_id;
-
- $this->pool_id = $a_pool_id;
- $this->pool = new ilObjBookingPool($this->pool_id, false);
-
- if($_GET['bkusr'])
- {
- $this->user_id_to_book = (int)$_GET['bkusr'];
- if(!ilObjUser::_exists($this->user_id_to_book)) {
- $this->ctrl->redirect($a_parent_obj, $a_parent_cmd);
- }
- $user_name_data = ilObjUser::_lookupName($this->user_id_to_book);
- $user_name = $user_name_data['lastname'].", ".$user_name_data['firstname'];
- } else {
- $this->ctrl->redirect($a_parent_obj, 'render');
- }
-
- $this->setId("bkaobj".$a_ref_id);
-
- parent::__construct($a_parent_obj, $a_parent_cmd);
-
- $this->setTitle($this->lng->txt("book_assign_object").": ".$user_name);
-
- $this->addColumn($this->lng->txt("title"), "title");
- $this->addColumn($this->lng->txt("description"));
- if ($this->pool->getScheduleType() != ilObjBookingPool::TYPE_FIX_SCHEDULE) {
- $this->addColumn($this->lng->txt("available"));
- }
- $this->addColumn($this->lng->txt("action"));
-
- //Fix this order field
- //$this->setDefaultOrderField("title");
- //$this->setDefaultOrderDirection("asc");
-
- $this->setEnableHeader(true);
- //$this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd));
- $this->setRowTemplate("tpl.booking_assign_object_row.html", "Modules/BookingManager");
-
- $this->getItems();
-
- }
-
- /**
- * Gather data and build rows
- * @param array $filter
- */
- function getItems()
- {
- $data = array();
- $obj_items = ilBookingObject::getList($this->pool_id);
- foreach($obj_items as $item)
- {
- if($this->pool->getScheduleType() == ilObjBookingPool::TYPE_FIX_SCHEDULE ||
- empty(ilBookingReservation::getObjectReservationForUser($item['booking_object_id'], $this->user_id_to_book)))
- {
- $this->ctrl->setParameterByClass('ilbookingobjectgui', 'bkusr', $this->user_id_to_book);
- $this->ctrl->setParameterByClass('ilbookingobjectgui', 'object_id', $item['booking_object_id']);
- $this->ctrl->setParameterByClass('ilbookingobjectgui', 'part_view',ilBookingParticipantGUI::PARTICIPANT_VIEW);
- $data[] = array(
- 'object_id' => $item['booking_object_id'],
- 'title' => $item['title'],
- 'description' => $item['description'],
- 'nr_items' => ilBookingReservation::numAvailableFromObjectNoSchedule($item['booking_object_id']).'/'.$item['nr_items'],
- 'url_assign'=> $this->ctrl->getLinkTargetByClass("ilbookingobjectgui", 'book')
- );
- $this->ctrl->setParameterByClass('ilbookingobjectgui', 'bkusr', '');
- $this->ctrl->setParameterByClass('ilbookingobjectgui', 'object_id', '');
- $this->ctrl->setParameterByClass('ilbookingobjectgui', 'part_view','');
- }
- }
- $this->setData($data);
- }
-
- /**
- * Fill table row
- * @param array $a_set
- */
- protected function fillRow($a_set)
- {
- if ($this->pool->getScheduleType() != ilObjBookingPool::TYPE_FIX_SCHEDULE) {
- $this->tpl->setCurrentBlock("available");
- $this->tpl->setVariable("TXT_AVAILABLE", $a_set['nr_items']);
- $this->tpl->parseCurrentBlock();
- }
- $this->tpl->setVariable("TXT_TITLE", $a_set['title']);
- $this->tpl->setVariable("TXT_DESCRIPTION", $a_set['description']);
- $this->tpl->setVariable("TXT_ACTION", $this->lng->txt("book_assign"));
- $this->tpl->setVariable("URL_ACTION", $a_set['url_assign']);
- }
+ /**
+ * @var ilAccessHandler
+ */
+ protected $access;
+
+ /**
+ * @var ilObjUser
+ */
+ protected $user;
+
+ /**
+ * @var int
+ */
+ protected $ref_id;
+
+ /**
+ * @var int
+ */
+ protected $pool_id;
+
+ /**
+ * @var int
+ */
+ protected $user_id_to_book;
+
+ /**
+ * @var ilObjBookingPool
+ */
+ //protected $bp_object;
+
+ /**
+ * @var int
+ */
+ protected $current_bookings; // [int]
+
+ /**
+ * @var array
+ */
+ protected $filter; // [array]
+
+ /**
+ * @var array
+ */
+ protected $objects; // array
+
+ /**
+ * @var ilObjBookingPool
+ */
+ protected $pool;
+
+ /**
+ * Constructor
+ * @param ilBookingParticipantGUI $a_parent_obj
+ * @param string $a_parent_cmd
+ * @param int $a_ref_id
+ * @param int $a_pool_id
+ * @param int $a_user_id // user id to be assigned
+ */
+ public function __construct(ilBookingParticipantGUI $a_parent_obj, $a_parent_cmd, $a_ref_id, $a_pool_id)
+ {
+ global $DIC;
+
+ $this->ctrl = $DIC->ctrl();
+ $this->lng = $DIC->language();
+ $this->user = $DIC->user();
+ $this->access = $DIC->access();
+ $this->ref_id = $a_ref_id;
+
+ $this->pool_id = $a_pool_id;
+ $this->pool = new ilObjBookingPool($this->pool_id, false);
+
+ if ($_GET['bkusr']) {
+ $this->user_id_to_book = (int) $_GET['bkusr'];
+ if (!ilObjUser::_exists($this->user_id_to_book)) {
+ $this->ctrl->redirect($a_parent_obj, $a_parent_cmd);
+ }
+ $user_name_data = ilObjUser::_lookupName($this->user_id_to_book);
+ $user_name = $user_name_data['lastname'] . ", " . $user_name_data['firstname'];
+ } else {
+ $this->ctrl->redirect($a_parent_obj, 'render');
+ }
+
+ $this->setId("bkaobj" . $a_ref_id);
+
+ parent::__construct($a_parent_obj, $a_parent_cmd);
+
+ $this->setTitle($this->lng->txt("book_assign_object") . ": " . $user_name);
+
+ $this->addColumn($this->lng->txt("title"), "title");
+ $this->addColumn($this->lng->txt("description"));
+ if ($this->pool->getScheduleType() != ilObjBookingPool::TYPE_FIX_SCHEDULE) {
+ $this->addColumn($this->lng->txt("available"));
+ }
+ $this->addColumn($this->lng->txt("action"));
+
+ //Fix this order field
+ //$this->setDefaultOrderField("title");
+ //$this->setDefaultOrderDirection("asc");
+
+ $this->setEnableHeader(true);
+ //$this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd));
+ $this->setRowTemplate("tpl.booking_assign_object_row.html", "Modules/BookingManager");
+
+ $this->getItems();
+ }
+
+ /**
+ * Gather data and build rows
+ * @param array $filter
+ */
+ public function getItems()
+ {
+ $data = array();
+ $obj_items = ilBookingObject::getList($this->pool_id);
+ foreach ($obj_items as $item) {
+ if ($this->pool->getScheduleType() == ilObjBookingPool::TYPE_FIX_SCHEDULE ||
+ empty(ilBookingReservation::getObjectReservationForUser($item['booking_object_id'], $this->user_id_to_book))) {
+ $this->ctrl->setParameterByClass('ilbookingobjectgui', 'bkusr', $this->user_id_to_book);
+ $this->ctrl->setParameterByClass('ilbookingobjectgui', 'object_id', $item['booking_object_id']);
+ $this->ctrl->setParameterByClass('ilbookingobjectgui', 'part_view', ilBookingParticipantGUI::PARTICIPANT_VIEW);
+ $data[] = array(
+ 'object_id' => $item['booking_object_id'],
+ 'title' => $item['title'],
+ 'description' => $item['description'],
+ 'nr_items' => ilBookingReservation::numAvailableFromObjectNoSchedule($item['booking_object_id']) . '/' . $item['nr_items'],
+ 'url_assign'=> $this->ctrl->getLinkTargetByClass("ilbookingobjectgui", 'book')
+ );
+ $this->ctrl->setParameterByClass('ilbookingobjectgui', 'bkusr', '');
+ $this->ctrl->setParameterByClass('ilbookingobjectgui', 'object_id', '');
+ $this->ctrl->setParameterByClass('ilbookingobjectgui', 'part_view', '');
+ }
+ }
+ $this->setData($data);
+ }
+
+ /**
+ * Fill table row
+ * @param array $a_set
+ */
+ protected function fillRow($a_set)
+ {
+ if ($this->pool->getScheduleType() != ilObjBookingPool::TYPE_FIX_SCHEDULE) {
+ $this->tpl->setCurrentBlock("available");
+ $this->tpl->setVariable("TXT_AVAILABLE", $a_set['nr_items']);
+ $this->tpl->parseCurrentBlock();
+ }
+ $this->tpl->setVariable("TXT_TITLE", $a_set['title']);
+ $this->tpl->setVariable("TXT_DESCRIPTION", $a_set['description']);
+ $this->tpl->setVariable("TXT_ACTION", $this->lng->txt("book_assign"));
+ $this->tpl->setVariable("URL_ACTION", $a_set['url_assign']);
+ }
}
-
-?>
\ No newline at end of file
diff --git a/Modules/BookingManager/classes/class.ilBookingAssignParticipantsTableGUI.php b/Modules/BookingManager/classes/class.ilBookingAssignParticipantsTableGUI.php
index 400891e2d5b675920b96ae8b22761e4ebc61d396..95891791d32ab9f2d89933011955b921f18157ed 100644
--- a/Modules/BookingManager/classes/class.ilBookingAssignParticipantsTableGUI.php
+++ b/Modules/BookingManager/classes/class.ilBookingAssignParticipantsTableGUI.php
@@ -11,148 +11,146 @@
*/
class ilBookingAssignParticipantsTableGUI extends ilTable2GUI
{
- /**
- * @var ilAccessHandler
- */
- protected $access;
-
- /**
- * @var ilObjUser
- */
- protected $user;
-
- /**
- * @var int
- */
- protected $ref_id;
-
- /**
- * @var int
- */
- protected $pool_id;
-
- /**
- * @var int
- */
- protected $bp_object_id;
-
- /**
- * @var ilObjBookingPool
- */
- protected $bp_object;
-
- /**
- * @var int
- */
- protected $current_bookings; // [int]
-
- /**
- * @var array
- */
- protected $filter; // [array]
-
- /**
- * @var array
- */
- protected $objects; // array
+ /**
+ * @var ilAccessHandler
+ */
+ protected $access;
+
+ /**
+ * @var ilObjUser
+ */
+ protected $user;
+
+ /**
+ * @var int
+ */
+ protected $ref_id;
+
+ /**
+ * @var int
+ */
+ protected $pool_id;
+
+ /**
+ * @var int
+ */
+ protected $bp_object_id;
+
+ /**
+ * @var ilObjBookingPool
+ */
+ protected $bp_object;
+
+ /**
+ * @var int
+ */
+ protected $current_bookings; // [int]
+
+ /**
+ * @var array
+ */
+ protected $filter; // [array]
+
+ /**
+ * @var array
+ */
+ protected $objects; // array
/**
* @var ilObjBookingPool
*/
protected $pool;
- /**
- * Constructor
- * @param ilBookingObjectGUI $a_parent_obj
- * @param string $a_parent_cmd
- * @param int $a_ref_id
- * @param int $a_pool_id
- * @param int $a_booking_obj_id //booking object to assign users.
- */
- function __construct(ilBookingObjectGUI $a_parent_obj, $a_parent_cmd, $a_ref_id, $a_pool_id, $a_booking_obj_id)
- {
- global $DIC;
-
- $this->ctrl = $DIC->ctrl();
- $this->lng = $DIC->language();
- $this->user = $DIC->user();
- $this->access = $DIC->access();
- $this->ref_id = $a_ref_id;
- $this->bp_object_id = $a_booking_obj_id;
- $this->pool_id = $a_pool_id;
- $this->bp_object = new ilBookingObject($a_booking_obj_id);
- $this->pool = new ilObjBookingPool($this->pool_id, false);
-
- $this->setId("bkaprt".$a_ref_id);
-
- parent::__construct($a_parent_obj, $a_parent_cmd);
-
- $this->setTitle($this->lng->txt("book_assign_participant").": ".$this->bp_object->getTitle());
-
- $this->addColumn("", "", 1);
- $this->addColumn($this->lng->txt("name"), "name");
+ /**
+ * Constructor
+ * @param ilBookingObjectGUI $a_parent_obj
+ * @param string $a_parent_cmd
+ * @param int $a_ref_id
+ * @param int $a_pool_id
+ * @param int $a_booking_obj_id //booking object to assign users.
+ */
+ public function __construct(ilBookingObjectGUI $a_parent_obj, $a_parent_cmd, $a_ref_id, $a_pool_id, $a_booking_obj_id)
+ {
+ global $DIC;
+
+ $this->ctrl = $DIC->ctrl();
+ $this->lng = $DIC->language();
+ $this->user = $DIC->user();
+ $this->access = $DIC->access();
+ $this->ref_id = $a_ref_id;
+ $this->bp_object_id = $a_booking_obj_id;
+ $this->pool_id = $a_pool_id;
+ $this->bp_object = new ilBookingObject($a_booking_obj_id);
+ $this->pool = new ilObjBookingPool($this->pool_id, false);
+
+ $this->setId("bkaprt" . $a_ref_id);
+
+ parent::__construct($a_parent_obj, $a_parent_cmd);
+
+ $this->setTitle($this->lng->txt("book_assign_participant") . ": " . $this->bp_object->getTitle());
+
+ $this->addColumn("", "", 1);
+ $this->addColumn($this->lng->txt("name"), "name");
if ($this->pool->getScheduleType() != ilObjBookingPool::TYPE_FIX_SCHEDULE) {
$this->addColumn($this->lng->txt("book_bobj"));
}
- $this->addColumn($this->lng->txt("action"));
+ $this->addColumn($this->lng->txt("action"));
- $this->setDefaultOrderField("name");
- $this->setDefaultOrderDirection("asc");
+ $this->setDefaultOrderField("name");
+ $this->setDefaultOrderDirection("asc");
- $this->setEnableHeader(true);
- $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd));
- $this->setRowTemplate("tpl.booking_assign_participant_row.html", "Modules/BookingManager");
+ $this->setEnableHeader(true);
+ $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd));
+ $this->setRowTemplate("tpl.booking_assign_participant_row.html", "Modules/BookingManager");
- $this->addHiddenInput('object_id', $a_booking_obj_id);
- if($this->pool->getScheduleType() != ilObjBookingPool::TYPE_FIX_SCHEDULE) {
+ $this->addHiddenInput('object_id', $a_booking_obj_id);
+ if ($this->pool->getScheduleType() != ilObjBookingPool::TYPE_FIX_SCHEDULE) {
$this->setSelectAllCheckbox('mass');
$this->addMultiCommand("bookMultipleParticipants", $this->lng->txt("assign"));
}
- $this->getItems();
-
-
- if($this->pool->getScheduleType() == ilObjBookingPool::TYPE_NO_SCHEDULE)
- {
- ilUtil::sendInfo(
- sprintf(
- $this->lng->txt("book_objects_available"),
- ilBookingReservation::numAvailableFromObjectNoSchedule($a_booking_obj_id)
- )
- );
- }
-
- }
-
- /**
- * Gather data and build rows
- */
- function getItems()
- {
- include_once "Modules/BookingManager/classes/class.ilBookingParticipant.php";
- if ($this->pool->getScheduleType() == ilObjBookingPool::TYPE_FIX_SCHEDULE) {
+ $this->getItems();
+
+
+ if ($this->pool->getScheduleType() == ilObjBookingPool::TYPE_NO_SCHEDULE) {
+ ilUtil::sendInfo(
+ sprintf(
+ $this->lng->txt("book_objects_available"),
+ ilBookingReservation::numAvailableFromObjectNoSchedule($a_booking_obj_id)
+ )
+ );
+ }
+ }
+
+ /**
+ * Gather data and build rows
+ */
+ public function getItems()
+ {
+ include_once "Modules/BookingManager/classes/class.ilBookingParticipant.php";
+ if ($this->pool->getScheduleType() == ilObjBookingPool::TYPE_FIX_SCHEDULE) {
$data = ilBookingParticipant::getList($this->pool_id, []);
} else {
$data = ilBookingParticipant::getAssignableParticipants($this->bp_object_id);
}
- $this->setMaxCount(sizeof($data));
- $this->setData($data);
- }
-
- /**
- * Fill table row
- * @param array $a_set
- */
- protected function fillRow($a_set)
- {
- if($this->pool->getScheduleType() != ilObjBookingPool::TYPE_FIX_SCHEDULE) {
+ $this->setMaxCount(sizeof($data));
+ $this->setData($data);
+ }
+
+ /**
+ * Fill table row
+ * @param array $a_set
+ */
+ protected function fillRow($a_set)
+ {
+ if ($this->pool->getScheduleType() != ilObjBookingPool::TYPE_FIX_SCHEDULE) {
$this->tpl->setCurrentBlock("multi");
$this->tpl->setVariable("MULTI_ID", $a_set['user_id']);
$this->tpl->parseCurrentBlock();
}
- $this->tpl->setVariable("TXT_NAME", $a_set['name']);
- $this->tpl->setCurrentBlock('object_titles');
+ $this->tpl->setVariable("TXT_NAME", $a_set['name']);
+ $this->tpl->setCurrentBlock('object_titles');
if ($this->pool->getScheduleType() != ilObjBookingPool::TYPE_FIX_SCHEDULE) {
foreach ($a_set['object_title'] as $obj_title) {
@@ -164,16 +162,13 @@ class ilBookingAssignParticipantsTableGUI extends ilTable2GUI
$this->tpl->parseCurrentBlock();
}
- $this->ctrl->setParameter($this->parent_obj, 'bkusr', $a_set['user_id']);
- $this->ctrl->setParameter($this->parent_obj, 'object_id', $this->bp_object_id);
+ $this->ctrl->setParameter($this->parent_obj, 'bkusr', $a_set['user_id']);
+ $this->ctrl->setParameter($this->parent_obj, 'object_id', $this->bp_object_id);
- $this->tpl->setVariable("TXT_ACTION", $this->lng->txt("book_assign"));
- $this->tpl->setVariable("URL_ACTION", $this->ctrl->getLinkTarget($this->parent_obj, 'book'));
+ $this->tpl->setVariable("TXT_ACTION", $this->lng->txt("book_assign"));
+ $this->tpl->setVariable("URL_ACTION", $this->ctrl->getLinkTarget($this->parent_obj, 'book'));
- $this->ctrl->setParameter($this->parent_obj, 'bkusr', '');
- $this->ctrl->setParameter($this->parent_obj, 'object_id', '');
-
- }
+ $this->ctrl->setParameter($this->parent_obj, 'bkusr', '');
+ $this->ctrl->setParameter($this->parent_obj, 'object_id', '');
+ }
}
-
-?>
\ No newline at end of file
diff --git a/Modules/BookingManager/classes/class.ilBookingObject.php b/Modules/BookingManager/classes/class.ilBookingObject.php
index 6ebc25c8b1d4cd0ede3ec64ce2379a3bac56ddd2..d77f8c8f57f3a20a769fb8ff8fba6fafa9064e96 100644
--- a/Modules/BookingManager/classes/class.ilBookingObject.php
+++ b/Modules/BookingManager/classes/class.ilBookingObject.php
@@ -11,594 +11,573 @@
*/
class ilBookingObject
{
- /**
- * @var ilDB
- */
- protected $db;
-
- protected $id; // int
- protected $pool_id; // int
- protected $title; // string
- protected $description; // string
- protected $nr_of_items; // int
- protected $schedule_id; // int
- protected $info_file; // string
- protected $post_text; // string
- protected $post_file; // string
-
- /**
- * Constructor
- *
- * if id is given will read dataset from db
- *
- * @param int $a_id
- */
- function __construct($a_id = NULL)
- {
- global $DIC;
-
- $this->db = $DIC->database();
- $this->id = (int)$a_id;
- $this->read();
- }
-
- /**
- * Get id
- * @return int
- */
- function getId()
- {
- return $this->id;
- }
-
- /**
- * Set object title
- * @param string $a_title
- */
- function setTitle($a_title)
- {
- $this->title = $a_title;
- }
-
- /**
- * Get object title
- * @return string
- */
- function getTitle()
- {
- return $this->title;
- }
-
- /**
- * Set object description
- * @param string $a_value
- */
- function setDescription($a_value)
- {
- $this->description = $a_value;
- }
-
- /**
- * Get object description
- * @return string
- */
- function getDescription()
- {
- return $this->description;
- }
-
- /**
- * Set booking pool id
- * @param int $a_pool_id
- */
- function setPoolId($a_pool_id)
- {
- $this->pool_id = (int)$a_pool_id;
- }
-
- /**
- * Get booking pool id
- * @return int
- */
- function getPoolId()
- {
- return $this->pool_id;
- }
-
- /**
- * Set booking schedule id
- * @param int $a_schedule_id
- */
- function setScheduleId($a_schedule_id)
- {
- $this->schedule_id = (int)$a_schedule_id;
- }
-
- /**
- * Get booking schedule id
- * @return int
- */
- function getScheduleId()
- {
- return $this->schedule_id;
- }
-
- /**
- * Set number of items
- * @param int $a_value
- */
- function setNrOfItems($a_value)
- {
- $this->nr_of_items = (int)$a_value;
- }
-
- /**
- * Get number of items
- * @return int
- */
- function getNrOfItems()
- {
- return $this->nr_of_items;
- }
-
- /**
- * Set info file
- * @param string $a_value
- */
- function setFile($a_value)
- {
- $this->info_file = $a_value;
- }
-
- /**
- * Get info file
- * @return string
- */
- function getFile()
- {
- return $this->info_file;
- }
-
- /**
- * Get path to info file
- */
- function getFileFullPath()
- {
- if($this->id && $this->info_file)
- {
- $path = $this->initStorage($this->id, "file");
- return $path.$this->info_file;
- }
- }
-
- /**
- * Upload new info file
- *
- * @param array $a_upload
- * @return bool
- */
- function uploadFile(array $a_upload)
- {
- if(!$this->id)
- {
- return false;
- }
-
- $this->deleteFile();
-
- $path = $this->initStorage($this->id, "file");
- $original = $a_upload["name"];
- if (ilUtil::moveUploadedFile($a_upload["tmp_name"], $original, $path.$original))
- {
- chmod($path.$original, 0770);
-
- $this->setFile($original);
- return true;
- }
- return false;
- }
-
- /**
- * remove existing info file
- */
- public function deleteFile()
- {
- if($this->id)
- {
- $path = $this->getFileFullPath();
- if($path)
- {
- @unlink($path);
- $this->setFile(null);
- }
- }
- }
-
- /**
- * Set post text
- * @param string $a_value
- */
- function setPostText($a_value)
- {
- $this->post_text = $a_value;
- }
-
- /**
- * Get post text
- * @return string
- */
- function getPostText()
- {
- return $this->post_text;
- }
-
- /**
- * Set post file
- * @param string $a_value
- */
- function setPostFile($a_value)
- {
- $this->post_file = $a_value;
- }
-
- /**
- * Get post file
- * @return string
- */
- function getPostFile()
- {
- return $this->post_file;
- }
-
- /**
- * Get path to post file
- */
- function getPostFileFullPath()
- {
- if($this->id && $this->post_file)
- {
- $path = $this->initStorage($this->id, "post");
- return $path.$this->post_file;
- }
- }
-
- /**
- * Upload new post file
- *
- * @param array $a_upload
- * @return bool
- */
- function uploadPostFile(array $a_upload)
- {
- if(!$this->id)
- {
- return false;
- }
-
- $this->deletePostFile();
-
- $path = $this->initStorage($this->id, "post");
- $original = $a_upload["name"];
-
- if (ilUtil::moveUploadedFile($a_upload["tmp_name"], $original, $path.$original))
- {
- chmod($path.$original, 0770);
-
- $this->setPostFile($original);
- return true;
- }
- return false;
- }
-
- /**
- * remove existing post file
- */
- public function deletePostFile()
- {
- if($this->id)
- {
- $path = $this->getPostFileFullPath();
- if($path)
- {
- @unlink($path);
- $this->setPostFile(null);
- }
- }
- }
-
- /**
- * remove existing files
- */
- public function deleteFiles()
- {
- if($this->id)
- {
- include_once "Modules/BookingManager/classes/class.ilFSStorageBooking.php";
- $storage = new ilFSStorageBooking($this->id);
- $storage->delete();
-
- $this->setFile(null);
- $this->setPostFile(null);
- }
- }
-
- /**
- * Init file system storage
- *
- * @param type $a_id
- * @param type $a_subdir
- * @return string
- */
- public static function initStorage($a_id, $a_subdir = null)
- {
- include_once "Modules/BookingManager/classes/class.ilFSStorageBooking.php";
- $storage = new ilFSStorageBooking($a_id);
- $storage->create();
-
- $path = $storage->getAbsolutePath()."/";
-
- if($a_subdir)
- {
- $path .= $a_subdir."/";
-
- if(!is_dir($path))
- {
- mkdir($path);
- }
- }
-
- return $path;
- }
-
- /**
- * Get dataset from db
- */
- protected function read()
- {
- $ilDB = $this->db;
-
- if($this->id)
- {
- $set = $ilDB->query('SELECT *'.
- ' FROM booking_object'.
- ' WHERE booking_object_id = '.$ilDB->quote($this->id, 'integer'));
- $row = $ilDB->fetchAssoc($set);
- $this->setTitle($row['title']);
- $this->setDescription($row['description']);
- $this->setPoolId($row['pool_id']);
- $this->setScheduleId($row['schedule_id']);
- $this->setNrOfItems($row['nr_items']);
- $this->setFile($row['info_file']);
- $this->setPostText($row['post_text']);
- $this->setPostFile($row['post_file']);
- }
- }
-
- /**
- * Parse properties for sql statements
- * @return array
- */
- protected function getDBFields()
- {
- $fields = array(
- 'title' => array('text', $this->getTitle()),
- 'description' => array('text', $this->getDescription()),
- 'schedule_id' => array('text', $this->getScheduleId()),
- 'nr_items' => array('text', $this->getNrOfItems()),
- 'info_file' => array('text', $this->getFile()),
- 'post_text' => array('text', $this->getPostText()),
- 'post_file' => array('text', $this->getPostFile())
- );
-
- return $fields;
- }
-
- /**
- * Create new entry in db
- * @return bool
- */
- function save()
- {
- $ilDB = $this->db;
-
- if($this->id)
- {
- return false;
- }
-
- $this->id = $ilDB->nextId('booking_object');
-
- $fields = $this->getDBFields();
- $fields['booking_object_id'] = array('integer', $this->id);
- $fields['pool_id'] = array('integer', $this->getPoolId());
-
- return $ilDB->insert('booking_object', $fields);
- }
-
- /**
- * Update entry in db
- * @return bool
- */
- function update()
- {
- $ilDB = $this->db;
-
- if(!$this->id)
- {
- return false;
- }
-
- $fields = $this->getDBFields();
-
- return $ilDB->update('booking_object', $fields,
- array('booking_object_id'=>array('integer', $this->id)));
- }
-
- /**
- * Get list of booking objects for given type
- * @param int $a_pool_id
- * @param string $a_title
- * @return array
- */
- static function getList($a_pool_id, $a_title = null)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $sql = 'SELECT *'.
- ' FROM booking_object'.
- ' WHERE pool_id = '.$ilDB->quote($a_pool_id, 'integer');
-
- if($a_title)
- {
- $sql .= ' AND ('.$ilDB->like('title', 'text', '%'.$a_title.'%').
- ' OR '.$ilDB->like('description', 'text', '%'.$a_title.'%').')';
- }
-
- $sql .= ' ORDER BY title';
-
- $set = $ilDB->query($sql);
- $res = array();
- while($row = $ilDB->fetchAssoc($set))
- {
- $res[] = $row;
- }
- return $res;
- }
-
- /**
- * Get number of booking objects for given booking pool id.
- * @param int $a_pool_id
- * @return int
- */
- static function getNumberOfObjectsForPool($a_pool_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $sql = 'SELECT count(*) as count'.
- ' FROM booking_object'.
- ' WHERE pool_id = '.$ilDB->quote($a_pool_id, 'integer');
- $set = $ilDB->query($sql);
- $rec = $ilDB->fetchAssoc($set);
-
- return $rec["count"];
- }
-
- /**
- * Get all booking pool object ids from an specific booking pool.
- * @param int $a_pool_id
- * @return array
- */
- static function getObjectsForPool(int $a_pool_id):array
- {
- global $DIC;
- $ilDB = $DIC->database();
-
- $set = $ilDB->query("SELECT booking_object_id".
- " FROM booking_object".
- " WHERE pool_id = ".$ilDB->quote($a_pool_id, 'integer'));
-
- $objects = array();
- while($row = $ilDB->fetchAssoc($set)) {
- $objects[] = $row['booking_object_id'];
- }
-
- return $objects;
- }
-
-
- /**
- * Delete single entry
- * @return bool
- */
- function delete()
- {
- $ilDB = $this->db;
-
- if($this->id)
- {
- $this->deleteFiles();
-
- return $ilDB->manipulate('DELETE FROM booking_object'.
- ' WHERE booking_object_id = '.$ilDB->quote($this->id, 'integer'));
- }
- }
-
- /**
- * Get nr of available items
- * @param array $a_obj_ids
- * @return array
- */
- static function getNrOfItemsForObjects(array $a_obj_ids)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $map = array();
-
- $set = $ilDB->query("SELECT booking_object_id,nr_items".
- " FROM booking_object".
- " WHERE ".$ilDB->in("booking_object_id", $a_obj_ids, "", "integer"));
- while($row = $ilDB->fetchAssoc($set))
- {
- $map[$row["booking_object_id"]] = $row["nr_items"];
- }
-
- return $map;
- }
-
- public function doClone($a_pool_id, $a_schedule_map = null)
- {
- $new_obj = new self();
- $new_obj->setPoolId($a_pool_id);
- $new_obj->setTitle($this->getTitle());
- $new_obj->setDescription($this->getDescription());
- $new_obj->setNrOfItems($this->getNrOfItems());
- $new_obj->setFile($this->getFile());
- $new_obj->setPostText($this->getPostText());
- $new_obj->setPostFile($this->getPostFile());
-
- if($a_schedule_map)
- {
- $schedule_id = $this->getScheduleId();
- if($schedule_id)
- {
- $new_obj->setScheduleId($a_schedule_map[$schedule_id]);
- }
- }
-
- $new_obj->save();
-
- // files
- $source = $this->initStorage($this->getId());
- $target = $new_obj->initStorage($new_obj->getId());
- ilUtil::rCopy($source, $target);
- }
-
- /**
- * Lookup pool id
- *
- * @param int $object_id
- * @return int
- */
- public static function lookupPoolId($object_id)
- {
- global $DIC;
-
- $db = $DIC->database();
- $set = $db->queryF("SELECT pool_id FROM booking_object ".
- " WHERE booking_object_id = %s ",
- array("integer"),
- array($object_id)
- );
- $rec = $db->fetchAssoc($set);
- return (int) $rec["pool_id"];
- }
-
+ /**
+ * @var ilDB
+ */
+ protected $db;
+
+ protected $id; // int
+ protected $pool_id; // int
+ protected $title; // string
+ protected $description; // string
+ protected $nr_of_items; // int
+ protected $schedule_id; // int
+ protected $info_file; // string
+ protected $post_text; // string
+ protected $post_file; // string
+
+ /**
+ * Constructor
+ *
+ * if id is given will read dataset from db
+ *
+ * @param int $a_id
+ */
+ public function __construct($a_id = null)
+ {
+ global $DIC;
+
+ $this->db = $DIC->database();
+ $this->id = (int) $a_id;
+ $this->read();
+ }
+
+ /**
+ * Get id
+ * @return int
+ */
+ public function getId()
+ {
+ return $this->id;
+ }
+
+ /**
+ * Set object title
+ * @param string $a_title
+ */
+ public function setTitle($a_title)
+ {
+ $this->title = $a_title;
+ }
+
+ /**
+ * Get object title
+ * @return string
+ */
+ public function getTitle()
+ {
+ return $this->title;
+ }
+
+ /**
+ * Set object description
+ * @param string $a_value
+ */
+ public function setDescription($a_value)
+ {
+ $this->description = $a_value;
+ }
+
+ /**
+ * Get object description
+ * @return string
+ */
+ public function getDescription()
+ {
+ return $this->description;
+ }
+
+ /**
+ * Set booking pool id
+ * @param int $a_pool_id
+ */
+ public function setPoolId($a_pool_id)
+ {
+ $this->pool_id = (int) $a_pool_id;
+ }
+
+ /**
+ * Get booking pool id
+ * @return int
+ */
+ public function getPoolId()
+ {
+ return $this->pool_id;
+ }
+
+ /**
+ * Set booking schedule id
+ * @param int $a_schedule_id
+ */
+ public function setScheduleId($a_schedule_id)
+ {
+ $this->schedule_id = (int) $a_schedule_id;
+ }
+
+ /**
+ * Get booking schedule id
+ * @return int
+ */
+ public function getScheduleId()
+ {
+ return $this->schedule_id;
+ }
+
+ /**
+ * Set number of items
+ * @param int $a_value
+ */
+ public function setNrOfItems($a_value)
+ {
+ $this->nr_of_items = (int) $a_value;
+ }
+
+ /**
+ * Get number of items
+ * @return int
+ */
+ public function getNrOfItems()
+ {
+ return $this->nr_of_items;
+ }
+
+ /**
+ * Set info file
+ * @param string $a_value
+ */
+ public function setFile($a_value)
+ {
+ $this->info_file = $a_value;
+ }
+
+ /**
+ * Get info file
+ * @return string
+ */
+ public function getFile()
+ {
+ return $this->info_file;
+ }
+
+ /**
+ * Get path to info file
+ */
+ public function getFileFullPath()
+ {
+ if ($this->id && $this->info_file) {
+ $path = $this->initStorage($this->id, "file");
+ return $path . $this->info_file;
+ }
+ }
+
+ /**
+ * Upload new info file
+ *
+ * @param array $a_upload
+ * @return bool
+ */
+ public function uploadFile(array $a_upload)
+ {
+ if (!$this->id) {
+ return false;
+ }
+
+ $this->deleteFile();
+
+ $path = $this->initStorage($this->id, "file");
+ $original = $a_upload["name"];
+ if (ilUtil::moveUploadedFile($a_upload["tmp_name"], $original, $path . $original)) {
+ chmod($path . $original, 0770);
+
+ $this->setFile($original);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * remove existing info file
+ */
+ public function deleteFile()
+ {
+ if ($this->id) {
+ $path = $this->getFileFullPath();
+ if ($path) {
+ @unlink($path);
+ $this->setFile(null);
+ }
+ }
+ }
+
+ /**
+ * Set post text
+ * @param string $a_value
+ */
+ public function setPostText($a_value)
+ {
+ $this->post_text = $a_value;
+ }
+
+ /**
+ * Get post text
+ * @return string
+ */
+ public function getPostText()
+ {
+ return $this->post_text;
+ }
+
+ /**
+ * Set post file
+ * @param string $a_value
+ */
+ public function setPostFile($a_value)
+ {
+ $this->post_file = $a_value;
+ }
+
+ /**
+ * Get post file
+ * @return string
+ */
+ public function getPostFile()
+ {
+ return $this->post_file;
+ }
+
+ /**
+ * Get path to post file
+ */
+ public function getPostFileFullPath()
+ {
+ if ($this->id && $this->post_file) {
+ $path = $this->initStorage($this->id, "post");
+ return $path . $this->post_file;
+ }
+ }
+
+ /**
+ * Upload new post file
+ *
+ * @param array $a_upload
+ * @return bool
+ */
+ public function uploadPostFile(array $a_upload)
+ {
+ if (!$this->id) {
+ return false;
+ }
+
+ $this->deletePostFile();
+
+ $path = $this->initStorage($this->id, "post");
+ $original = $a_upload["name"];
+
+ if (ilUtil::moveUploadedFile($a_upload["tmp_name"], $original, $path . $original)) {
+ chmod($path . $original, 0770);
+
+ $this->setPostFile($original);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * remove existing post file
+ */
+ public function deletePostFile()
+ {
+ if ($this->id) {
+ $path = $this->getPostFileFullPath();
+ if ($path) {
+ @unlink($path);
+ $this->setPostFile(null);
+ }
+ }
+ }
+
+ /**
+ * remove existing files
+ */
+ public function deleteFiles()
+ {
+ if ($this->id) {
+ include_once "Modules/BookingManager/classes/class.ilFSStorageBooking.php";
+ $storage = new ilFSStorageBooking($this->id);
+ $storage->delete();
+
+ $this->setFile(null);
+ $this->setPostFile(null);
+ }
+ }
+
+ /**
+ * Init file system storage
+ *
+ * @param type $a_id
+ * @param type $a_subdir
+ * @return string
+ */
+ public static function initStorage($a_id, $a_subdir = null)
+ {
+ include_once "Modules/BookingManager/classes/class.ilFSStorageBooking.php";
+ $storage = new ilFSStorageBooking($a_id);
+ $storage->create();
+
+ $path = $storage->getAbsolutePath() . "/";
+
+ if ($a_subdir) {
+ $path .= $a_subdir . "/";
+
+ if (!is_dir($path)) {
+ mkdir($path);
+ }
+ }
+
+ return $path;
+ }
+
+ /**
+ * Get dataset from db
+ */
+ protected function read()
+ {
+ $ilDB = $this->db;
+
+ if ($this->id) {
+ $set = $ilDB->query('SELECT *' .
+ ' FROM booking_object' .
+ ' WHERE booking_object_id = ' . $ilDB->quote($this->id, 'integer'));
+ $row = $ilDB->fetchAssoc($set);
+ $this->setTitle($row['title']);
+ $this->setDescription($row['description']);
+ $this->setPoolId($row['pool_id']);
+ $this->setScheduleId($row['schedule_id']);
+ $this->setNrOfItems($row['nr_items']);
+ $this->setFile($row['info_file']);
+ $this->setPostText($row['post_text']);
+ $this->setPostFile($row['post_file']);
+ }
+ }
+
+ /**
+ * Parse properties for sql statements
+ * @return array
+ */
+ protected function getDBFields()
+ {
+ $fields = array(
+ 'title' => array('text', $this->getTitle()),
+ 'description' => array('text', $this->getDescription()),
+ 'schedule_id' => array('text', $this->getScheduleId()),
+ 'nr_items' => array('text', $this->getNrOfItems()),
+ 'info_file' => array('text', $this->getFile()),
+ 'post_text' => array('text', $this->getPostText()),
+ 'post_file' => array('text', $this->getPostFile())
+ );
+
+ return $fields;
+ }
+
+ /**
+ * Create new entry in db
+ * @return bool
+ */
+ public function save()
+ {
+ $ilDB = $this->db;
+
+ if ($this->id) {
+ return false;
+ }
+
+ $this->id = $ilDB->nextId('booking_object');
+
+ $fields = $this->getDBFields();
+ $fields['booking_object_id'] = array('integer', $this->id);
+ $fields['pool_id'] = array('integer', $this->getPoolId());
+
+ return $ilDB->insert('booking_object', $fields);
+ }
+
+ /**
+ * Update entry in db
+ * @return bool
+ */
+ public function update()
+ {
+ $ilDB = $this->db;
+
+ if (!$this->id) {
+ return false;
+ }
+
+ $fields = $this->getDBFields();
+
+ return $ilDB->update(
+ 'booking_object',
+ $fields,
+ array('booking_object_id'=>array('integer', $this->id))
+ );
+ }
+
+ /**
+ * Get list of booking objects for given type
+ * @param int $a_pool_id
+ * @param string $a_title
+ * @return array
+ */
+ public static function getList($a_pool_id, $a_title = null)
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ $sql = 'SELECT *' .
+ ' FROM booking_object' .
+ ' WHERE pool_id = ' . $ilDB->quote($a_pool_id, 'integer');
+
+ if ($a_title) {
+ $sql .= ' AND (' . $ilDB->like('title', 'text', '%' . $a_title . '%') .
+ ' OR ' . $ilDB->like('description', 'text', '%' . $a_title . '%') . ')';
+ }
+
+ $sql .= ' ORDER BY title';
+
+ $set = $ilDB->query($sql);
+ $res = array();
+ while ($row = $ilDB->fetchAssoc($set)) {
+ $res[] = $row;
+ }
+ return $res;
+ }
+
+ /**
+ * Get number of booking objects for given booking pool id.
+ * @param int $a_pool_id
+ * @return int
+ */
+ public static function getNumberOfObjectsForPool($a_pool_id)
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ $sql = 'SELECT count(*) as count' .
+ ' FROM booking_object' .
+ ' WHERE pool_id = ' . $ilDB->quote($a_pool_id, 'integer');
+ $set = $ilDB->query($sql);
+ $rec = $ilDB->fetchAssoc($set);
+
+ return $rec["count"];
+ }
+
+ /**
+ * Get all booking pool object ids from an specific booking pool.
+ * @param int $a_pool_id
+ * @return array
+ */
+ public static function getObjectsForPool(int $a_pool_id) : array
+ {
+ global $DIC;
+ $ilDB = $DIC->database();
+
+ $set = $ilDB->query("SELECT booking_object_id" .
+ " FROM booking_object" .
+ " WHERE pool_id = " . $ilDB->quote($a_pool_id, 'integer'));
+
+ $objects = array();
+ while ($row = $ilDB->fetchAssoc($set)) {
+ $objects[] = $row['booking_object_id'];
+ }
+
+ return $objects;
+ }
+
+
+ /**
+ * Delete single entry
+ * @return bool
+ */
+ public function delete()
+ {
+ $ilDB = $this->db;
+
+ if ($this->id) {
+ $this->deleteFiles();
+
+ return $ilDB->manipulate('DELETE FROM booking_object' .
+ ' WHERE booking_object_id = ' . $ilDB->quote($this->id, 'integer'));
+ }
+ }
+
+ /**
+ * Get nr of available items
+ * @param array $a_obj_ids
+ * @return array
+ */
+ public static function getNrOfItemsForObjects(array $a_obj_ids)
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ $map = array();
+
+ $set = $ilDB->query("SELECT booking_object_id,nr_items" .
+ " FROM booking_object" .
+ " WHERE " . $ilDB->in("booking_object_id", $a_obj_ids, "", "integer"));
+ while ($row = $ilDB->fetchAssoc($set)) {
+ $map[$row["booking_object_id"]] = $row["nr_items"];
+ }
+
+ return $map;
+ }
+
+ public function doClone($a_pool_id, $a_schedule_map = null)
+ {
+ $new_obj = new self();
+ $new_obj->setPoolId($a_pool_id);
+ $new_obj->setTitle($this->getTitle());
+ $new_obj->setDescription($this->getDescription());
+ $new_obj->setNrOfItems($this->getNrOfItems());
+ $new_obj->setFile($this->getFile());
+ $new_obj->setPostText($this->getPostText());
+ $new_obj->setPostFile($this->getPostFile());
+
+ if ($a_schedule_map) {
+ $schedule_id = $this->getScheduleId();
+ if ($schedule_id) {
+ $new_obj->setScheduleId($a_schedule_map[$schedule_id]);
+ }
+ }
+
+ $new_obj->save();
+
+ // files
+ $source = $this->initStorage($this->getId());
+ $target = $new_obj->initStorage($new_obj->getId());
+ ilUtil::rCopy($source, $target);
+ }
+
+ /**
+ * Lookup pool id
+ *
+ * @param int $object_id
+ * @return int
+ */
+ public static function lookupPoolId($object_id)
+ {
+ global $DIC;
+
+ $db = $DIC->database();
+ $set = $db->queryF(
+ "SELECT pool_id FROM booking_object " .
+ " WHERE booking_object_id = %s ",
+ array("integer"),
+ array($object_id)
+ );
+ $rec = $db->fetchAssoc($set);
+ return (int) $rec["pool_id"];
+ }
}
-
-?>
\ No newline at end of file
diff --git a/Modules/BookingManager/classes/class.ilBookingObjectGUI.php b/Modules/BookingManager/classes/class.ilBookingObjectGUI.php
index ff89be64ffca7e5d415b25eaa805299a367a2c44..06ea97e23c8de5ebb683c4468364dcfd110f7b2e 100644
--- a/Modules/BookingManager/classes/class.ilBookingObjectGUI.php
+++ b/Modules/BookingManager/classes/class.ilBookingObjectGUI.php
@@ -12,752 +12,704 @@ require_once "./Services/Object/classes/class.ilObjectGUI.php";
*/
class ilBookingObjectGUI
{
- /**
- * @var ilCtrl
- */
- protected $ctrl;
-
- /**
- * @var ilTemplate
- */
- protected $tpl;
-
- /**
- * @var ilLanguage
- */
- protected $lng;
-
- /**
- * @var ilAccessHandler
- */
- protected $access;
-
- /**
- * @var ilTabsGUI
- */
- protected $tabs;
-
- /**
- * @var ilHelpGUI
- */
- protected $help;
-
- /**
- * @var ilObjectDataCache
- */
- protected $obj_data_cache;
-
- /**
- * @var ilObjUser
- */
- protected $user;
-
- protected $ref_id; // [int]
- protected $pool_id; // [int]
- protected $pool_has_schedule; // [bool]
- protected $pool_overall_limit; // [int]
- protected $user_to_deasign;
- /**
- * @var int
- */
- protected $object_id;
-
- /**
- * Constructor
- * @param object $a_parent_obj
- */
- function __construct($a_parent_obj)
- {
- global $DIC;
-
- $this->ctrl = $DIC->ctrl();
- $this->tpl = $DIC["tpl"];
- $this->lng = $DIC->language();
- $this->access = $DIC->access();
- $this->tabs = $DIC->tabs();
- $this->help = $DIC["ilHelp"];
- $this->obj_data_cache = $DIC["ilObjDataCache"];
- $this->user = $DIC->user();
- $this->ref_id = $a_parent_obj->ref_id;
- $this->pool_id = $a_parent_obj->object->getId();
- $this->pool_gui = $a_parent_obj;
- $this->pool_has_schedule =
- ($a_parent_obj->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE);
- $this->pool_overall_limit = $this->pool_has_schedule
- ? null
- : $a_parent_obj->object->getOverallLimit();
-
- $this->object_id = (int) $_REQUEST['object_id'];
- $this->user_to_deasign = (int) $_REQUEST['bkusr'];
- $this->rsv_ids = array_map('intval', explode(";", $_GET["rsv_ids"]));
- }
-
- /**
- * main switch
- */
- function executeCommand()
- {
- $ilCtrl = $this->ctrl;
-
- $next_class = $ilCtrl->getNextClass($this);
-
- switch($next_class)
- {
-
- case "ilpropertyformgui":
- // only case is currently adv metadata internal link in info settings, see #24497
- $form = $this->initForm();
- $this->ctrl->forwardCommand($form);
- break;
-
- default:
- $cmd = $ilCtrl->getCmd("render");
- $this->$cmd();
- break;
- }
- return true;
- }
-
- /**
- * Render list of booking objects
- *
- * uses ilBookingObjectsTableGUI
- */
- function render()
- {
- $this->pool_gui->showNoScheduleMessage();
-
- $tpl = $this->tpl;
- $ilCtrl = $this->ctrl;
- $lng = $this->lng;
- $ilAccess = $this->access;
-
- if ($ilAccess->checkAccess('write', '', $this->ref_id))
- {
- include_once 'Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php';
- $bar = new ilToolbarGUI;
- $bar->addButton($lng->txt('book_add_object'), $ilCtrl->getLinkTarget($this, 'create'));
- $bar = $bar->getHTML();
- }
-
- $tpl->setPermanentLink('book', $this->ref_id);
-
- include_once 'Modules/BookingManager/classes/class.ilBookingObjectsTableGUI.php';
- $table = new ilBookingObjectsTableGUI($this, 'render', $this->ref_id, $this->pool_id, $this->pool_has_schedule, $this->pool_overall_limit);
- $tpl->setContent($bar.$table->getHTML());
- }
-
- function applyFilter()
- {
- include_once 'Modules/BookingManager/classes/class.ilBookingObjectsTableGUI.php';
- $table = new ilBookingObjectsTableGUI($this, 'render', $this->ref_id, $this->pool_id, $this->pool_has_schedule, $this->pool_overall_limit, $this->repo_parent, $this->repo_parent_call);
- $table->resetOffset();
- $table->writeFilterToSession();
- $this->render();
- }
-
- function resetFilter()
- {
- include_once 'Modules/BookingManager/classes/class.ilBookingObjectsTableGUI.php';
- $table = new ilBookingObjectsTableGUI($this, 'render', $this->ref_id, $this->pool_id, $this->pool_has_schedule, $this->pool_overall_limit, $this->repo_parent, $this->repo_parent_call);
- $table->resetOffset();
- $table->resetFilter();
- $this->render();
- }
-
- /**
- * Render creation form
- */
- function create(ilPropertyFormGUI $a_form = null)
- {
+ /**
+ * @var ilCtrl
+ */
+ protected $ctrl;
+
+ /**
+ * @var ilTemplate
+ */
+ protected $tpl;
+
+ /**
+ * @var ilLanguage
+ */
+ protected $lng;
+
+ /**
+ * @var ilAccessHandler
+ */
+ protected $access;
+
+ /**
+ * @var ilTabsGUI
+ */
+ protected $tabs;
+
+ /**
+ * @var ilHelpGUI
+ */
+ protected $help;
+
+ /**
+ * @var ilObjectDataCache
+ */
+ protected $obj_data_cache;
+
+ /**
+ * @var ilObjUser
+ */
+ protected $user;
+
+ protected $ref_id; // [int]
+ protected $pool_id; // [int]
+ protected $pool_has_schedule; // [bool]
+ protected $pool_overall_limit; // [int]
+ protected $user_to_deasign;
+ /**
+ * @var int
+ */
+ protected $object_id;
+
+ /**
+ * Constructor
+ * @param object $a_parent_obj
+ */
+ public function __construct($a_parent_obj)
+ {
+ global $DIC;
+
+ $this->ctrl = $DIC->ctrl();
+ $this->tpl = $DIC["tpl"];
+ $this->lng = $DIC->language();
+ $this->access = $DIC->access();
+ $this->tabs = $DIC->tabs();
+ $this->help = $DIC["ilHelp"];
+ $this->obj_data_cache = $DIC["ilObjDataCache"];
+ $this->user = $DIC->user();
+ $this->ref_id = $a_parent_obj->ref_id;
+ $this->pool_id = $a_parent_obj->object->getId();
+ $this->pool_gui = $a_parent_obj;
+ $this->pool_has_schedule =
+ ($a_parent_obj->object->getScheduleType() != ilObjBookingPool::TYPE_NO_SCHEDULE);
+ $this->pool_overall_limit = $this->pool_has_schedule
+ ? null
+ : $a_parent_obj->object->getOverallLimit();
+
+ $this->object_id = (int) $_REQUEST['object_id'];
+ $this->user_to_deasign = (int) $_REQUEST['bkusr'];
+ $this->rsv_ids = array_map('intval', explode(";", $_GET["rsv_ids"]));
+ }
+
+ /**
+ * main switch
+ */
+ public function executeCommand()
+ {
+ $ilCtrl = $this->ctrl;
+
+ $next_class = $ilCtrl->getNextClass($this);
+
+ switch ($next_class) {
+
+ case "ilpropertyformgui":
+ // only case is currently adv metadata internal link in info settings, see #24497
+ $form = $this->initForm();
+ $this->ctrl->forwardCommand($form);
+ break;
+
+ default:
+ $cmd = $ilCtrl->getCmd("render");
+ $this->$cmd();
+ break;
+ }
+ return true;
+ }
+
+ /**
+ * Render list of booking objects
+ *
+ * uses ilBookingObjectsTableGUI
+ */
+ public function render()
+ {
+ $this->pool_gui->showNoScheduleMessage();
+
+ $tpl = $this->tpl;
+ $ilCtrl = $this->ctrl;
+ $lng = $this->lng;
+ $ilAccess = $this->access;
+
+ if ($ilAccess->checkAccess('write', '', $this->ref_id)) {
+ include_once 'Services/UIComponent/Toolbar/classes/class.ilToolbarGUI.php';
+ $bar = new ilToolbarGUI;
+ $bar->addButton($lng->txt('book_add_object'), $ilCtrl->getLinkTarget($this, 'create'));
+ $bar = $bar->getHTML();
+ }
+
+ $tpl->setPermanentLink('book', $this->ref_id);
+
+ include_once 'Modules/BookingManager/classes/class.ilBookingObjectsTableGUI.php';
+ $table = new ilBookingObjectsTableGUI($this, 'render', $this->ref_id, $this->pool_id, $this->pool_has_schedule, $this->pool_overall_limit);
+ $tpl->setContent($bar . $table->getHTML());
+ }
+
+ public function applyFilter()
+ {
+ include_once 'Modules/BookingManager/classes/class.ilBookingObjectsTableGUI.php';
+ $table = new ilBookingObjectsTableGUI($this, 'render', $this->ref_id, $this->pool_id, $this->pool_has_schedule, $this->pool_overall_limit, $this->repo_parent, $this->repo_parent_call);
+ $table->resetOffset();
+ $table->writeFilterToSession();
+ $this->render();
+ }
+
+ public function resetFilter()
+ {
+ include_once 'Modules/BookingManager/classes/class.ilBookingObjectsTableGUI.php';
+ $table = new ilBookingObjectsTableGUI($this, 'render', $this->ref_id, $this->pool_id, $this->pool_has_schedule, $this->pool_overall_limit, $this->repo_parent, $this->repo_parent_call);
+ $table->resetOffset();
+ $table->resetFilter();
+ $this->render();
+ }
+
+ /**
+ * Render creation form
+ */
+ public function create(ilPropertyFormGUI $a_form = null)
+ {
if (!$this->access->checkAccess('write', '', $this->ref_id)) {
return;
}
- $ilCtrl = $this->ctrl;
- $tpl = $this->tpl;
- $lng = $this->lng;
- $ilTabs = $this->tabs;
-
- $ilTabs->clearTargets();
- $ilTabs->setBackTarget($lng->txt('book_back_to_list'), $ilCtrl->getLinkTarget($this, 'render'));
-
- $this->setHelpId('create');
-
- if(!$a_form)
- {
- $a_form = $this->initForm();
- }
- $tpl->setContent($a_form->getHTML());
- }
-
- /**
- * Render edit form
- */
- function edit(ilPropertyFormGUI $a_form = null)
+ $ilCtrl = $this->ctrl;
+ $tpl = $this->tpl;
+ $lng = $this->lng;
+ $ilTabs = $this->tabs;
+
+ $ilTabs->clearTargets();
+ $ilTabs->setBackTarget($lng->txt('book_back_to_list'), $ilCtrl->getLinkTarget($this, 'render'));
+
+ $this->setHelpId('create');
+
+ if (!$a_form) {
+ $a_form = $this->initForm();
+ }
+ $tpl->setContent($a_form->getHTML());
+ }
+
+ /**
+ * Render edit form
+ */
+ public function edit(ilPropertyFormGUI $a_form = null)
{
if (!$this->access->checkAccess('write', '', $this->ref_id)) {
return;
}
$tpl = $this->tpl;
- $ilCtrl = $this->ctrl;
- $ilTabs = $this->tabs;
- $lng = $this->lng;
-
- $ilTabs->clearTargets();
- $ilTabs->setBackTarget($lng->txt('book_back_to_list'), $ilCtrl->getLinkTarget($this, 'render'));
-
- $this->setHelpId('edit');
-
- if(!$a_form)
- {
- $a_form = $this->initForm('edit', $this->object_id);
- }
- $tpl->setContent($a_form->getHTML());
- }
-
- protected function setHelpId($a_id)
- {
- $ilHelp = $this->help;
-
- $object_subtype = $this->pool_has_schedule
- ? '-schedule'
- : '-nonschedule';
-
- $ilHelp->setScreenIdComponent('book');
- $ilHelp->setScreenId('object'.$object_subtype);
- $ilHelp->setSubScreenId($a_id);
- }
-
- /**
- * Build property form
- * @param string $a_mode
- * @param int $id
- * @return object
- */
- function initForm($a_mode = "create", $id = NULL)
- {
- $lng = $this->lng;
- $ilCtrl = $this->ctrl;
- $ilObjDataCache = $this->obj_data_cache;
-
- include_once("Services/Form/classes/class.ilPropertyFormGUI.php");
-
- $form_gui = new ilPropertyFormGUI();
-
- $title = new ilTextInputGUI($lng->txt("title"), "title");
- $title->setRequired(true);
- $title->setSize(40);
- $title->setMaxLength(120);
- $form_gui->addItem($title);
-
- $desc = new ilTextAreaInputGUI($lng->txt("description"), "desc");
- $desc->setCols(70);
- $desc->setRows(15);
- $form_gui->addItem($desc);
-
- $file = new ilFileInputGUI($lng->txt("book_additional_info_file"), "file");
- $file->setALlowDeletion(true);
- $form_gui->addItem($file);
-
- $nr = new ilNumberInputGUI($lng->txt("booking_nr_of_items"), "items");
- $nr->setRequired(true);
- $nr->setSize(3);
- $nr->setMaxLength(3);
- $form_gui->addItem($nr);
-
- if($this->pool_has_schedule)
- {
- $options = array();
- include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';
- foreach(ilBookingSchedule::getList($ilObjDataCache->lookupObjId($this->ref_id)) as $schedule)
- {
- $options[$schedule["booking_schedule_id"]] = $schedule["title"];
- }
- $schedule = new ilSelectInputGUI($lng->txt("book_schedule"), "schedule");
- $schedule->setRequired(true);
- $schedule->setOptions($options);
- $form_gui->addItem($schedule);
- }
-
- $post = new ilFormSectionHeaderGUI();
- $post->setTitle($lng->txt("book_post_booking_information"));
- $form_gui->addItem($post);
-
- $pdesc = new ilTextAreaInputGUI($lng->txt("book_post_booking_text"), "post_text");
- $pdesc->setCols(70);
- $pdesc->setRows(15);
- $pdesc->setInfo($lng->txt("book_post_booking_text_info"));
- $form_gui->addItem($pdesc);
-
- $pfile = new ilFileInputGUI($lng->txt("book_post_booking_file"), "post_file");
- $pfile->setALlowDeletion(true);
- $form_gui->addItem($pfile);
-
- // #18214 - should also work for new objects
- include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php');
- $this->record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_EDITOR, "book", $this->pool_id, "bobj", $id);
- $this->record_gui->setPropertyForm($form_gui);
- $this->record_gui->parse();
-
- if ($a_mode == "edit")
- {
- $form_gui->setTitle($lng->txt("book_edit_object"));
-
- $item = new ilHiddenInputGUI('object_id');
- $item->setValue($id);
- $form_gui->addItem($item);
-
- include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
- $obj = new ilBookingObject($id);
- $title->setValue($obj->getTitle());
- $desc->setValue($obj->getDescription());
- $nr->setValue($obj->getNrOfItems());
- $pdesc->setValue($obj->getPostText());
- $file->setValue($obj->getFile());
- $pfile->setValue($obj->getPostFile());
-
- if(isset($schedule))
- {
- $schedule->setValue($obj->getScheduleId());
- }
-
- $form_gui->addCommandButton("update", $lng->txt("save"));
- }
- else
- {
- $form_gui->setTitle($lng->txt("book_add_object"));
- $form_gui->addCommandButton("save", $lng->txt("save"));
- $form_gui->addCommandButton("render", $lng->txt("cancel"));
- }
- $form_gui->setFormAction($ilCtrl->getFormAction($this));
-
- return $form_gui;
- }
-
- /**
- * Create new object dataset
- */
- function save()
- {
+ $ilCtrl = $this->ctrl;
+ $ilTabs = $this->tabs;
+ $lng = $this->lng;
+
+ $ilTabs->clearTargets();
+ $ilTabs->setBackTarget($lng->txt('book_back_to_list'), $ilCtrl->getLinkTarget($this, 'render'));
+
+ $this->setHelpId('edit');
+
+ if (!$a_form) {
+ $a_form = $this->initForm('edit', $this->object_id);
+ }
+ $tpl->setContent($a_form->getHTML());
+ }
+
+ protected function setHelpId($a_id)
+ {
+ $ilHelp = $this->help;
+
+ $object_subtype = $this->pool_has_schedule
+ ? '-schedule'
+ : '-nonschedule';
+
+ $ilHelp->setScreenIdComponent('book');
+ $ilHelp->setScreenId('object' . $object_subtype);
+ $ilHelp->setSubScreenId($a_id);
+ }
+
+ /**
+ * Build property form
+ * @param string $a_mode
+ * @param int $id
+ * @return object
+ */
+ public function initForm($a_mode = "create", $id = null)
+ {
+ $lng = $this->lng;
+ $ilCtrl = $this->ctrl;
+ $ilObjDataCache = $this->obj_data_cache;
+
+ include_once("Services/Form/classes/class.ilPropertyFormGUI.php");
+
+ $form_gui = new ilPropertyFormGUI();
+
+ $title = new ilTextInputGUI($lng->txt("title"), "title");
+ $title->setRequired(true);
+ $title->setSize(40);
+ $title->setMaxLength(120);
+ $form_gui->addItem($title);
+
+ $desc = new ilTextAreaInputGUI($lng->txt("description"), "desc");
+ $desc->setCols(70);
+ $desc->setRows(15);
+ $form_gui->addItem($desc);
+
+ $file = new ilFileInputGUI($lng->txt("book_additional_info_file"), "file");
+ $file->setALlowDeletion(true);
+ $form_gui->addItem($file);
+
+ $nr = new ilNumberInputGUI($lng->txt("booking_nr_of_items"), "items");
+ $nr->setRequired(true);
+ $nr->setSize(3);
+ $nr->setMaxLength(3);
+ $form_gui->addItem($nr);
+
+ if ($this->pool_has_schedule) {
+ $options = array();
+ include_once 'Modules/BookingManager/classes/class.ilBookingSchedule.php';
+ foreach (ilBookingSchedule::getList($ilObjDataCache->lookupObjId($this->ref_id)) as $schedule) {
+ $options[$schedule["booking_schedule_id"]] = $schedule["title"];
+ }
+ $schedule = new ilSelectInputGUI($lng->txt("book_schedule"), "schedule");
+ $schedule->setRequired(true);
+ $schedule->setOptions($options);
+ $form_gui->addItem($schedule);
+ }
+
+ $post = new ilFormSectionHeaderGUI();
+ $post->setTitle($lng->txt("book_post_booking_information"));
+ $form_gui->addItem($post);
+
+ $pdesc = new ilTextAreaInputGUI($lng->txt("book_post_booking_text"), "post_text");
+ $pdesc->setCols(70);
+ $pdesc->setRows(15);
+ $pdesc->setInfo($lng->txt("book_post_booking_text_info"));
+ $form_gui->addItem($pdesc);
+
+ $pfile = new ilFileInputGUI($lng->txt("book_post_booking_file"), "post_file");
+ $pfile->setALlowDeletion(true);
+ $form_gui->addItem($pfile);
+
+ // #18214 - should also work for new objects
+ include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php');
+ $this->record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_EDITOR, "book", $this->pool_id, "bobj", $id);
+ $this->record_gui->setPropertyForm($form_gui);
+ $this->record_gui->parse();
+
+ if ($a_mode == "edit") {
+ $form_gui->setTitle($lng->txt("book_edit_object"));
+
+ $item = new ilHiddenInputGUI('object_id');
+ $item->setValue($id);
+ $form_gui->addItem($item);
+
+ include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+ $obj = new ilBookingObject($id);
+ $title->setValue($obj->getTitle());
+ $desc->setValue($obj->getDescription());
+ $nr->setValue($obj->getNrOfItems());
+ $pdesc->setValue($obj->getPostText());
+ $file->setValue($obj->getFile());
+ $pfile->setValue($obj->getPostFile());
+
+ if (isset($schedule)) {
+ $schedule->setValue($obj->getScheduleId());
+ }
+
+ $form_gui->addCommandButton("update", $lng->txt("save"));
+ } else {
+ $form_gui->setTitle($lng->txt("book_add_object"));
+ $form_gui->addCommandButton("save", $lng->txt("save"));
+ $form_gui->addCommandButton("render", $lng->txt("cancel"));
+ }
+ $form_gui->setFormAction($ilCtrl->getFormAction($this));
+
+ return $form_gui;
+ }
+
+ /**
+ * Create new object dataset
+ */
+ public function save()
+ {
if (!$this->access->checkAccess('write', '', $this->ref_id)) {
return;
}
$ilCtrl = $this->ctrl;
- $lng = $this->lng;
-
- $form = $this->initForm();
- if($form->checkInput())
- {
- $valid = true;
- if($this->record_gui &&
- !$this->record_gui->importEditFormPostValues())
- {
- $valid = false;
- }
-
- if($valid)
- {
- include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
- $obj = new ilBookingObject;
- $obj->setPoolId($this->pool_id);
- $obj->setTitle($form->getInput("title"));
- $obj->setDescription($form->getInput("desc"));
- $obj->setNrOfItems($form->getInput("items"));
- $obj->setPostText($form->getInput("post_text"));
-
- if($this->pool_has_schedule)
- {
- $obj->setScheduleId($form->getInput("schedule"));
- }
-
- $obj->save();
-
- $file = $form->getItemByPostVar("file");
- if($_FILES["file"]["tmp_name"])
- {
- $obj->uploadFile($_FILES["file"]);
- }
- else if($file->getDeletionFlag())
- {
- $obj->deleteFile();
- }
-
- $pfile = $form->getItemByPostVar("post_file");
- if($_FILES["post_file"]["tmp_name"])
- {
- $obj->uploadPostFile($_FILES["post_file"]);
- }
- else if($pfile->getDeletionFlag())
- {
- $obj->deletePostFile();
- }
-
- $obj->update();
-
- if($this->record_gui)
- {
- $this->record_gui->writeEditForm(null, $obj->getId());
- }
-
- ilUtil::sendSuccess($lng->txt("book_object_added"), true);
- $ilCtrl->redirect($this, "render");
- }
- }
-
- $form->setValuesByPost();
- $this->create($form);
- }
-
- /**
- * Update object dataset
- */
- function update()
- {
+ $lng = $this->lng;
+
+ $form = $this->initForm();
+ if ($form->checkInput()) {
+ $valid = true;
+ if ($this->record_gui &&
+ !$this->record_gui->importEditFormPostValues()) {
+ $valid = false;
+ }
+
+ if ($valid) {
+ include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+ $obj = new ilBookingObject;
+ $obj->setPoolId($this->pool_id);
+ $obj->setTitle($form->getInput("title"));
+ $obj->setDescription($form->getInput("desc"));
+ $obj->setNrOfItems($form->getInput("items"));
+ $obj->setPostText($form->getInput("post_text"));
+
+ if ($this->pool_has_schedule) {
+ $obj->setScheduleId($form->getInput("schedule"));
+ }
+
+ $obj->save();
+
+ $file = $form->getItemByPostVar("file");
+ if ($_FILES["file"]["tmp_name"]) {
+ $obj->uploadFile($_FILES["file"]);
+ } elseif ($file->getDeletionFlag()) {
+ $obj->deleteFile();
+ }
+
+ $pfile = $form->getItemByPostVar("post_file");
+ if ($_FILES["post_file"]["tmp_name"]) {
+ $obj->uploadPostFile($_FILES["post_file"]);
+ } elseif ($pfile->getDeletionFlag()) {
+ $obj->deletePostFile();
+ }
+
+ $obj->update();
+
+ if ($this->record_gui) {
+ $this->record_gui->writeEditForm(null, $obj->getId());
+ }
+
+ ilUtil::sendSuccess($lng->txt("book_object_added"), true);
+ $ilCtrl->redirect($this, "render");
+ }
+ }
+
+ $form->setValuesByPost();
+ $this->create($form);
+ }
+
+ /**
+ * Update object dataset
+ */
+ public function update()
+ {
if (!$this->access->checkAccess('write', '', $this->ref_id)) {
return;
}
$lng = $this->lng;
- $ilCtrl = $this->ctrl;
-
- $form = $this->initForm('edit', $this->object_id);
- if($form->checkInput())
- {
- $valid = true;
- if($this->record_gui &&
- !$this->record_gui->importEditFormPostValues())
- {
- $valid = false;
- }
-
- if($valid)
- {
- include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
- $obj = new ilBookingObject($this->object_id);
- $obj->setTitle($form->getInput("title"));
- $obj->setDescription($form->getInput("desc"));
- $obj->setNrOfItems($form->getInput("items"));
- $obj->setPostText($form->getInput("post_text"));
-
- $file = $form->getItemByPostVar("file");
- if($_FILES["file"]["tmp_name"])
- {
- $obj->uploadFile($_FILES["file"]);
- }
- else if($file->getDeletionFlag())
- {
- $obj->deleteFile();
- }
-
- $pfile = $form->getItemByPostVar("post_file");
- if($_FILES["post_file"]["tmp_name"])
- {
- $obj->uploadPostFile($_FILES["post_file"]);
- }
- else if($pfile->getDeletionFlag())
- {
- $obj->deletePostFile();
- }
-
- if($this->pool_has_schedule)
- {
- $obj->setScheduleId($form->getInput("schedule"));
- }
-
- $obj->update();
-
- if($this->record_gui)
- {
- $this->record_gui->writeEditForm();
- }
-
- ilUtil::sendSuccess($lng->txt("book_object_updated"), true);
- $ilCtrl->redirect($this, "render");
- }
- }
-
- $form->setValuesByPost();
- $this->edit($form);
- }
-
- /**
- * Confirm delete
- */
- function confirmDelete()
- {
+ $ilCtrl = $this->ctrl;
+
+ $form = $this->initForm('edit', $this->object_id);
+ if ($form->checkInput()) {
+ $valid = true;
+ if ($this->record_gui &&
+ !$this->record_gui->importEditFormPostValues()) {
+ $valid = false;
+ }
+
+ if ($valid) {
+ include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+ $obj = new ilBookingObject($this->object_id);
+ $obj->setTitle($form->getInput("title"));
+ $obj->setDescription($form->getInput("desc"));
+ $obj->setNrOfItems($form->getInput("items"));
+ $obj->setPostText($form->getInput("post_text"));
+
+ $file = $form->getItemByPostVar("file");
+ if ($_FILES["file"]["tmp_name"]) {
+ $obj->uploadFile($_FILES["file"]);
+ } elseif ($file->getDeletionFlag()) {
+ $obj->deleteFile();
+ }
+
+ $pfile = $form->getItemByPostVar("post_file");
+ if ($_FILES["post_file"]["tmp_name"]) {
+ $obj->uploadPostFile($_FILES["post_file"]);
+ } elseif ($pfile->getDeletionFlag()) {
+ $obj->deletePostFile();
+ }
+
+ if ($this->pool_has_schedule) {
+ $obj->setScheduleId($form->getInput("schedule"));
+ }
+
+ $obj->update();
+
+ if ($this->record_gui) {
+ $this->record_gui->writeEditForm();
+ }
+
+ ilUtil::sendSuccess($lng->txt("book_object_updated"), true);
+ $ilCtrl->redirect($this, "render");
+ }
+ }
+
+ $form->setValuesByPost();
+ $this->edit($form);
+ }
+
+ /**
+ * Confirm delete
+ */
+ public function confirmDelete()
+ {
if (!$this->access->checkAccess('write', '', $this->ref_id)) {
return;
}
$ilCtrl = $this->ctrl;
- $lng = $this->lng;
- $tpl = $this->tpl;
- $ilTabs = $this->tabs;
-
- $ilTabs->clearTargets();
- $ilTabs->setBackTarget($lng->txt('book_back_to_list'), $ilCtrl->getLinkTarget($this, 'render'));
-
- include_once 'Services/Utilities/classes/class.ilConfirmationGUI.php';
- $conf = new ilConfirmationGUI();
- $conf->setFormAction($ilCtrl->getFormAction($this));
- $conf->setHeaderText($lng->txt('book_confirm_delete'));
-
- include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
- $type = new ilBookingObject($this->object_id);
- $conf->addItem('object_id', $this->object_id, $type->getTitle());
- $conf->setConfirm($lng->txt('delete'), 'delete');
- $conf->setCancel($lng->txt('cancel'), 'render');
-
- $tpl->setContent($conf->getHTML());
- }
-
- /**
- * Delete object
- */
- function delete()
- {
+ $lng = $this->lng;
+ $tpl = $this->tpl;
+ $ilTabs = $this->tabs;
+
+ $ilTabs->clearTargets();
+ $ilTabs->setBackTarget($lng->txt('book_back_to_list'), $ilCtrl->getLinkTarget($this, 'render'));
+
+ include_once 'Services/Utilities/classes/class.ilConfirmationGUI.php';
+ $conf = new ilConfirmationGUI();
+ $conf->setFormAction($ilCtrl->getFormAction($this));
+ $conf->setHeaderText($lng->txt('book_confirm_delete'));
+
+ include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+ $type = new ilBookingObject($this->object_id);
+ $conf->addItem('object_id', $this->object_id, $type->getTitle());
+ $conf->setConfirm($lng->txt('delete'), 'delete');
+ $conf->setCancel($lng->txt('cancel'), 'render');
+
+ $tpl->setContent($conf->getHTML());
+ }
+
+ /**
+ * Delete object
+ */
+ public function delete()
+ {
if (!$this->access->checkAccess('write', '', $this->ref_id)) {
return;
}
$ilCtrl = $this->ctrl;
- $lng = $this->lng;
-
- include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
- $obj = new ilBookingObject($this->object_id);
- $obj->delete();
-
- ilUtil::sendSuccess($lng->txt('book_object_deleted'), true);
- $ilCtrl->redirect($this, 'render');
- }
-
- function rsvConfirmCancelUser()
- {
- $ilCtrl = $this->ctrl;
- $lng = $this->lng;
- $tpl = $this->tpl;
-
- $id = $this->object_id;
- if(!$id)
- {
- return;
- }
-
- $this->setHelpId("cancel_booking");
-
- include_once 'Services/Utilities/classes/class.ilConfirmationGUI.php';
- $conf = new ilConfirmationGUI();
- $conf->setFormAction($ilCtrl->getFormAction($this));
- $conf->setHeaderText($lng->txt('book_confirm_cancel'));
-
- include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
- $type = new ilBookingObject($id);
- $conf->addItem('object_id', $id, $type->getTitle());
- if($this->user_to_deasign) {
- $conf->addHiddenItem('bkusr', $this->user_to_deasign);
- }
- if($_GET['part_view'] == ilBookingParticipantGUI::PARTICIPANT_VIEW) {
- $conf->addHiddenItem('part_view',ilBookingParticipantGUI::PARTICIPANT_VIEW);
- }
- $conf->setConfirm($lng->txt('book_set_cancel'), 'rsvCancelUser');
- $conf->setCancel($lng->txt('cancel'), 'render');
-
- $tpl->setContent($conf->getHTML());
- }
-
- function rsvCancelUser()
- {
- $ilCtrl = $this->ctrl;
- $lng = $this->lng;
-
- if($this->user_to_deasign) {
- $user_id = $this->user_to_deasign;
- } else {
- $user_id = $this->user->getId();
- }
-
- $id = $this->object_id;
- if(!$id || !$user_id) {
- return;
- }
-
- include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
- $id = ilBookingReservation::getObjectReservationForUser($id, $user_id);
- $obj = new ilBookingReservation($id);
- if ($obj->getUserId() != $user_id)
- {
- ilUtil::sendFailure($lng->txt('permission_denied'), true);
- $ilCtrl->redirect($this, 'render');
- }
-
- $obj->setStatus(ilBookingReservation::STATUS_CANCELLED);
- $obj->update();
-
- ilUtil::sendSuccess($lng->txt('settings_saved'));
- if($_POST['part_view'] == ilBookingParticipantGUI::PARTICIPANT_VIEW) {
- $this->ctrl->redirectByClass('ilbookingparticipantgui', 'render');
- } else {
- $ilCtrl->redirect($this, 'render');
- }
- }
-
- function deliverInfo()
- {
- $id = $this->object_id;
- if(!$id)
- {
- return;
- }
-
- include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
- $obj = new ilBookingObject($id);
- $file = $obj->getFileFullPath();
- if($file)
- {
- ilUtil::deliverFile($file, $obj->getFile());
- }
- }
-
- public function displayPostInfo()
- {
- $tpl = $this->tpl;
- $ilUser = $this->user;
- $lng = $this->lng;
- $ilCtrl = $this->ctrl;
-
- $id = $this->object_id;
- if(!$id)
- {
- return;
- }
-
-
- // placeholder
-
- include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
- $book_ids = ilBookingReservation::getObjectReservationForUser($id, $ilUser->getId(), true);
- $tmp = array();
- foreach($book_ids as $book_id)
- {
- if(in_array($book_id, $this->rsv_ids))
- {
- $obj = new ilBookingReservation($book_id);
- $from = $obj->getFrom();
- $to = $obj->getTo();
- if($from > time())
- {
- $tmp[$from."-".$to]++;
- }
- }
- }
-
- $olddt = ilDatePresentation::useRelativeDates();
- ilDatePresentation::setUseRelativeDates(false);
-
- $period = array();
- ksort($tmp);
- foreach($tmp as $time => $counter)
- {
- $time = explode("-", $time);
- $time = ilDatePresentation::formatPeriod(
- new ilDateTime($time[0], IL_CAL_UNIX),
- new ilDateTime($time[1], IL_CAL_UNIX));
- if($counter > 1)
- {
- $time .= " (".$counter.")";
- }
- $period[] = $time;
- }
- $book_id = array_shift($book_ids);
-
- ilDatePresentation::setUseRelativeDates($olddt);
-
-
- /*
- #23578 since Booking pool participants.
- $obj = new ilBookingReservation($book_id);
- if ($obj->getUserId() != $ilUser->getId())
- {
- return;
- }
- */
-
- include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
- $obj = new ilBookingObject($id);
- $pfile = $obj->getPostFile();
- $ptext = $obj->getPostText();
-
- $mytpl = new ilTemplate('tpl.booking_reservation_post.html', true, true, 'Modules/BookingManager');
- $mytpl->setVariable("TITLE", $lng->txt('book_post_booking_information'));
-
- if($ptext)
- {
- // placeholder
- $ptext = str_replace("[OBJECT]", $obj->getTitle(), $ptext);
- $ptext = str_replace("[PERIOD]", implode("
", $period), $ptext);
-
- $mytpl->setVariable("POST_TEXT", nl2br($ptext));
- }
-
- if($pfile)
- {
- $ilCtrl->setParameter($this, "object_id", $obj->getId());
- $url = $ilCtrl->getLinkTarget($this, 'deliverPostFile');
- $ilCtrl->setParameter($this, "object_id", "");
-
- $mytpl->setVariable("DOWNLOAD", $lng->txt('download'));
- $mytpl->setVariable("URL_FILE", $url);
- $mytpl->setVariable("TXT_FILE", $pfile);
- }
-
- $mytpl->setVariable("TXT_SUBMIT", $lng->txt('ok'));
- $mytpl->setVariable("URL_SUBMIT", $ilCtrl->getLinkTargetByClass('ilobjbookingpoolgui', 'render'));
-
- $tpl->setContent($mytpl->get());
- }
-
- public function deliverPostFile()
- {
- $ilUser = $this->user;
-
- $id = $this->object_id;
- if(!$id)
- {
- return;
- }
-
- include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
- $book_id = ilBookingReservation::getObjectReservationForUser($id, $ilUser->getId());
- $obj = new ilBookingReservation($book_id);
- if ($obj->getUserId() != $ilUser->getId())
- {
- return;
- }
-
- include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
- $obj = new ilBookingObject($id);
- $file = $obj->getPostFileFullPath();
- if($file)
- {
- ilUtil::deliverFile($file, $obj->getPostFile());
- }
- }
-
- //Table to assing participants to an object.
- //Todo move to a complete GUI class
- function assignParticipants()
- {
- $this->tabs->clearTargets();
- $this->tabs->setBackTarget($this->lng->txt('book_back_to_list'), $this->ctrl->getLinkTarget($this, 'render'));
-
- include_once("./Modules/BookingManager/classes/class.ilBookingAssignParticipantsTableGUI.php");
- $table = new ilBookingAssignParticipantsTableGUI($this, 'assignParticipants', $this->ref_id, $this->pool_id, $this->object_id);
-
- $this->tpl->setContent($table->getHTML());
- }
-}
+ $lng = $this->lng;
+
+ include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+ $obj = new ilBookingObject($this->object_id);
+ $obj->delete();
-?>
\ No newline at end of file
+ ilUtil::sendSuccess($lng->txt('book_object_deleted'), true);
+ $ilCtrl->redirect($this, 'render');
+ }
+
+ public function rsvConfirmCancelUser()
+ {
+ $ilCtrl = $this->ctrl;
+ $lng = $this->lng;
+ $tpl = $this->tpl;
+
+ $id = $this->object_id;
+ if (!$id) {
+ return;
+ }
+
+ $this->setHelpId("cancel_booking");
+
+ include_once 'Services/Utilities/classes/class.ilConfirmationGUI.php';
+ $conf = new ilConfirmationGUI();
+ $conf->setFormAction($ilCtrl->getFormAction($this));
+ $conf->setHeaderText($lng->txt('book_confirm_cancel'));
+
+ include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+ $type = new ilBookingObject($id);
+ $conf->addItem('object_id', $id, $type->getTitle());
+ if ($this->user_to_deasign) {
+ $conf->addHiddenItem('bkusr', $this->user_to_deasign);
+ }
+ if ($_GET['part_view'] == ilBookingParticipantGUI::PARTICIPANT_VIEW) {
+ $conf->addHiddenItem('part_view', ilBookingParticipantGUI::PARTICIPANT_VIEW);
+ }
+ $conf->setConfirm($lng->txt('book_set_cancel'), 'rsvCancelUser');
+ $conf->setCancel($lng->txt('cancel'), 'render');
+
+ $tpl->setContent($conf->getHTML());
+ }
+
+ public function rsvCancelUser()
+ {
+ $ilCtrl = $this->ctrl;
+ $lng = $this->lng;
+
+ if ($this->user_to_deasign) {
+ $user_id = $this->user_to_deasign;
+ } else {
+ $user_id = $this->user->getId();
+ }
+
+ $id = $this->object_id;
+ if (!$id || !$user_id) {
+ return;
+ }
+
+ include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
+ $id = ilBookingReservation::getObjectReservationForUser($id, $user_id);
+ $obj = new ilBookingReservation($id);
+ if ($obj->getUserId() != $user_id) {
+ ilUtil::sendFailure($lng->txt('permission_denied'), true);
+ $ilCtrl->redirect($this, 'render');
+ }
+
+ $obj->setStatus(ilBookingReservation::STATUS_CANCELLED);
+ $obj->update();
+
+ ilUtil::sendSuccess($lng->txt('settings_saved'));
+ if ($_POST['part_view'] == ilBookingParticipantGUI::PARTICIPANT_VIEW) {
+ $this->ctrl->redirectByClass('ilbookingparticipantgui', 'render');
+ } else {
+ $ilCtrl->redirect($this, 'render');
+ }
+ }
+
+ public function deliverInfo()
+ {
+ $id = $this->object_id;
+ if (!$id) {
+ return;
+ }
+
+ include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+ $obj = new ilBookingObject($id);
+ $file = $obj->getFileFullPath();
+ if ($file) {
+ ilUtil::deliverFile($file, $obj->getFile());
+ }
+ }
+
+ public function displayPostInfo()
+ {
+ $tpl = $this->tpl;
+ $ilUser = $this->user;
+ $lng = $this->lng;
+ $ilCtrl = $this->ctrl;
+
+ $id = $this->object_id;
+ if (!$id) {
+ return;
+ }
+
+
+ // placeholder
+
+ include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
+ $book_ids = ilBookingReservation::getObjectReservationForUser($id, $ilUser->getId(), true);
+ $tmp = array();
+ foreach ($book_ids as $book_id) {
+ if (in_array($book_id, $this->rsv_ids)) {
+ $obj = new ilBookingReservation($book_id);
+ $from = $obj->getFrom();
+ $to = $obj->getTo();
+ if ($from > time()) {
+ $tmp[$from . "-" . $to]++;
+ }
+ }
+ }
+
+ $olddt = ilDatePresentation::useRelativeDates();
+ ilDatePresentation::setUseRelativeDates(false);
+
+ $period = array();
+ ksort($tmp);
+ foreach ($tmp as $time => $counter) {
+ $time = explode("-", $time);
+ $time = ilDatePresentation::formatPeriod(
+ new ilDateTime($time[0], IL_CAL_UNIX),
+ new ilDateTime($time[1], IL_CAL_UNIX)
+ );
+ if ($counter > 1) {
+ $time .= " (" . $counter . ")";
+ }
+ $period[] = $time;
+ }
+ $book_id = array_shift($book_ids);
+
+ ilDatePresentation::setUseRelativeDates($olddt);
+
+
+ /*
+ #23578 since Booking pool participants.
+ $obj = new ilBookingReservation($book_id);
+ if ($obj->getUserId() != $ilUser->getId())
+ {
+ return;
+ }
+ */
+
+ include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+ $obj = new ilBookingObject($id);
+ $pfile = $obj->getPostFile();
+ $ptext = $obj->getPostText();
+
+ $mytpl = new ilTemplate('tpl.booking_reservation_post.html', true, true, 'Modules/BookingManager');
+ $mytpl->setVariable("TITLE", $lng->txt('book_post_booking_information'));
+
+ if ($ptext) {
+ // placeholder
+ $ptext = str_replace("[OBJECT]", $obj->getTitle(), $ptext);
+ $ptext = str_replace("[PERIOD]", implode("
", $period), $ptext);
+
+ $mytpl->setVariable("POST_TEXT", nl2br($ptext));
+ }
+
+ if ($pfile) {
+ $ilCtrl->setParameter($this, "object_id", $obj->getId());
+ $url = $ilCtrl->getLinkTarget($this, 'deliverPostFile');
+ $ilCtrl->setParameter($this, "object_id", "");
+
+ $mytpl->setVariable("DOWNLOAD", $lng->txt('download'));
+ $mytpl->setVariable("URL_FILE", $url);
+ $mytpl->setVariable("TXT_FILE", $pfile);
+ }
+
+ $mytpl->setVariable("TXT_SUBMIT", $lng->txt('ok'));
+ $mytpl->setVariable("URL_SUBMIT", $ilCtrl->getLinkTargetByClass('ilobjbookingpoolgui', 'render'));
+
+ $tpl->setContent($mytpl->get());
+ }
+
+ public function deliverPostFile()
+ {
+ $ilUser = $this->user;
+
+ $id = $this->object_id;
+ if (!$id) {
+ return;
+ }
+
+ include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
+ $book_id = ilBookingReservation::getObjectReservationForUser($id, $ilUser->getId());
+ $obj = new ilBookingReservation($book_id);
+ if ($obj->getUserId() != $ilUser->getId()) {
+ return;
+ }
+
+ include_once 'Modules/BookingManager/classes/class.ilBookingObject.php';
+ $obj = new ilBookingObject($id);
+ $file = $obj->getPostFileFullPath();
+ if ($file) {
+ ilUtil::deliverFile($file, $obj->getPostFile());
+ }
+ }
+
+ //Table to assing participants to an object.
+ //Todo move to a complete GUI class
+ public function assignParticipants()
+ {
+ $this->tabs->clearTargets();
+ $this->tabs->setBackTarget($this->lng->txt('book_back_to_list'), $this->ctrl->getLinkTarget($this, 'render'));
+
+ include_once("./Modules/BookingManager/classes/class.ilBookingAssignParticipantsTableGUI.php");
+ $table = new ilBookingAssignParticipantsTableGUI($this, 'assignParticipants', $this->ref_id, $this->pool_id, $this->object_id);
+
+ $this->tpl->setContent($table->getHTML());
+ }
+}
diff --git a/Modules/BookingManager/classes/class.ilBookingObjectsTableGUI.php b/Modules/BookingManager/classes/class.ilBookingObjectsTableGUI.php
index bfdc9d42ff86e918adccd6975f5569f8a43c93b3..039b752eda5f14106bdfc82fc0edcbae43afa656 100644
--- a/Modules/BookingManager/classes/class.ilBookingObjectsTableGUI.php
+++ b/Modules/BookingManager/classes/class.ilBookingObjectsTableGUI.php
@@ -6,466 +6,419 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php");
/**
* List booking objects (for booking type)
*
- * @author Jörg Lützenkirchen "; print_r($res); exit;
- return $res;
- }
-
- /**
- * Get all participants for a booking pool.
- * @param $a_booking_pool_id
- * @return array
- */
- static function getBookingPoolParticipants(integer $a_booking_pool_id) : array
- {
- global $DIC;
- $ilDB = $DIC->database();
- $sql = 'SELECT * FROM booking_member WHERE booking_pool_id = '.$ilDB->quote($a_booking_pool_id, 'integer');
-
- $set = $ilDB->query($sql);
-
- $res = array();
- while($row = $ilDB->fetchAssoc($set))
- {
- $res[] = $row['user_id'];
- }
-
- return $res;
- }
-
- /**
- *Get user data from db for an specific pool id.
- *
- * @param integer $a_pool_id
- * @return array
- */
- public static function getUserFilter($a_pool_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $res = array();
-
- $sql = "SELECT ud.usr_id,ud.lastname,ud.firstname,ud.login".
- " FROM usr_data ud ".
- " RIGHT JOIN booking_member m ON (ud.usr_id = m.user_id)".
- " WHERE ud.usr_id <> ".$ilDB->quote(ANONYMOUS_USER_ID, "integer").
- " AND m.booking_pool_id = ".$ilDB->quote($a_pool_id, "integer").
- " ORDER BY ud.lastname,ud.firstname";
-
- $set = $ilDB->query($sql);
- while($row = $ilDB->fetchAssoc($set))
- {
- $res[$row["usr_id"]] = $row["lastname"].", ".$row["firstname"].
- " (".$row["login"].")";
- }
-
- return $res;
- }
-
- /**
- * Returns true if the participant has a reservation for this object.
- * @param $a_booking_object_id
- * @param $a_participant_id
- * @return bool
- */
- protected function isParticipantAssigned($a_booking_object_id, $a_participant_id)
- {
- if(!empty(ilBookingReservation::getObjectReservationForUser($a_booking_object_id, $a_participant_id))){
- return true;
- } else {
- return false;
- }
- }
-}
\ No newline at end of file
+ protected $lng;
+ protected $db;
+ protected $participant_id;
+ protected $booking_pool_id;
+ protected $is_new;
+
+ /**
+ * ilBookingParticipant constructor.
+ * @param $a_user_id integer
+ * @param $a_booking_pool_id integer
+ */
+ public function __construct($a_user_id, $a_booking_pool_id)
+ {
+ if (!ilObjUser::_exists($a_user_id) || !ilObjBookingPool::_exists($a_booking_pool_id)) {
+ return false;
+ }
+
+ global $DIC;
+ $this->lng = $DIC->language();
+ $this->db = $DIC->database();
+ $this->il_user = $DIC->user();
+
+ $this->participant_id = $a_user_id;
+ $this->booking_pool_id = $a_booking_pool_id;
+
+ // if read and not exists, store it in db.
+ if (!$this->read()) {
+ $this->save();
+ $this->is_new = true;
+ } else {
+ $this->is_new = false;
+ }
+ }
+
+ /**
+ * Read from DB
+ * @return int|bool participant id if found.
+ */
+ protected function read()
+ {
+ $query = 'SELECT participant_id FROM booking_member' .
+ ' WHERE user_id = ' . $this->db->quote($this->participant_id, 'integer') .
+ ' AND booking_pool_id = ' . $this->db->quote($this->booking_pool_id, 'integer');
+
+ $set = $this->db->query($query);
+ $row = $this->db->fetchAssoc($set);
+ if (empty($row)) {
+ return false;
+ } else {
+ return $row['participant_id'];
+ }
+ }
+
+ /**
+ * Save booking participant in DB
+ */
+ protected function save()
+ {
+ $assigner_id = $this->il_user->getId();
+ $next_id = $this->db->nextId('booking_member');
+
+ $query = 'INSERT INTO booking_member' .
+ ' (participant_id, user_id, booking_pool_id, assigner_user_id)' .
+ ' VALUES (' . $this->db->quote($next_id, 'integer') .
+ ',' . $this->db->quote($this->participant_id, 'integer') .
+ ',' . $this->db->quote($this->booking_pool_id, 'integer') .
+ ',' . $this->db->quote($assigner_id, 'integer') . ')';
+
+ $this->db->manipulate($query);
+ }
+
+ /**
+ * @return bool IF read or created
+ */
+ public function getIsNew()
+ {
+ return $this->is_new;
+ }
+
+ /**
+ * Get participants who can not have a reservation for this booking pool object id.
+ *
+ * @param integer $a_bp_object_id booking pool object
+ * @return array formatted data to display in gui table.
+ */
+ public static function getAssignableParticipants($a_bp_object_id)
+ {
+ $booking_object = new ilBookingObject($a_bp_object_id);
+ $pool_id = $booking_object->getPoolId();
+ $pool = new ilObjBookingPool($pool_id, false);
+ $overall_limit = (int) $pool->getOverallLimit();
+
+ $res = array();
+
+ $members = ilBookingReservation::getMembersWithoutReservation($a_bp_object_id);
+
+ foreach ($members as $member_id) {
+ //check if the user reached the limit of booking in this booking pool.
+ $total_reservations = ilBookingReservation::isBookingPoolLimitReachedByUser($member_id, $pool_id);
+
+ if ($overall_limit == 0 || ($overall_limit > 0 && $total_reservations < $overall_limit)) {
+ $user_name = ilObjUser::_lookupName($member_id);
+ $name = $user_name['lastname'] . ", " . $user_name['firstname'];
+ $index = $a_bp_object_id . "_" . $member_id;
+
+ if (!isset($res[$index])) {
+ $res[$index] = array(
+ "user_id" => $member_id,
+ "object_title" => array($booking_object->getTitle()),
+ "name" => $name
+ );
+ } else {
+ if (!in_array($booking_object->getTitle(), $res[$index]['object_title'])) {
+ array_push($res[$index]['object_title'], $booking_object->getTitle());
+ }
+ }
+ }
+ }
+
+ return $res;
+ }
+
+ public static function getList($a_booking_pool, array $a_filter = null, $a_object_id = null)
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+ $lng = $DIC->language();
+ $ctrl = $DIC->ctrl();
+
+ $res = array();
+
+ $query = 'SELECT bm.user_id, bm.booking_pool_id, br.object_id, bo.title, br.status' .
+ ' FROM booking_member bm' .
+ ' LEFT JOIN booking_reservation br ON (bm.user_id = br.user_id)' .
+ ' LEFT JOIN booking_object bo ON (br.object_id = bo.booking_object_id AND bo.pool_id = ' . $ilDB->quote($a_booking_pool, 'integer') . ')';
+
+ $where = array('bm.booking_pool_id =' . $ilDB->quote($a_booking_pool, 'integer'));
+ if ($a_object_id) {
+ $where[] = 'br.object_id = ' . $ilDB->quote($a_object_id, 'integer');
+ }
+ if ($a_filter['title']) {
+ $where[] = '(' . $ilDB->like('title', 'text', '%' . $a_filter['title'] . '%') .
+ ' OR ' . $ilDB->like('description', 'text', '%' . $a_filter['title'] . '%') . ')';
+ }
+ if ($a_filter['user_id']) {
+ $where[] = 'bm.user_id = ' . $ilDB->quote($a_filter['user_id'], 'integer');
+ }
+
+ $query .= ' WHERE ' . implode(' AND ', $where);
+
+ $set = $ilDB->query($query);
+
+ while ($row = $ilDB->fetchAssoc($set)) {
+ $status = $row['status'];
+ //Nothing to show if the status is canceled when filtering by object
+ if ($status == ilBookingReservation::STATUS_CANCELLED && $a_object_id) {
+ continue;
+ }
+
+ $user_name = ilObjUser::_lookupName($row['user_id']);
+ $name = $user_name['lastname'] . ", " . $user_name['firstname'];
+ $index = $a_booking_pool . "_" . $row['user_id'];
+ $actions = array();
+
+ if (!isset($res[$index])) {
+ $res[$index] = array(
+ "object_title" => array(),
+ "name" => $name
+ );
+
+ if ($status != ilBookingReservation::STATUS_CANCELLED && $row['title'] != "") {
+ $res[$index]['object_title'] = array($row['title']);
+ $res[$index]['obj_count'] = 1;
+ $res[$index]['object_ids'][] = $row['object_id'];
+ }
+ } else {
+ if ($row['title'] != "" && (!in_array(
+ $row['title'],
+ $res[$index]['object_title']
+ ) && $status != ilBookingReservation::STATUS_CANCELLED)) {
+ array_push($res[$index]['object_title'], $row['title']);
+ $res[$index]['obj_count'] = $res[$index]['obj_count'] + 1;
+ $res[$index]['object_ids'][] = $row['object_id'];
+ }
+ }
+ $res[$index]['user_id'] = $row['user_id'];
+ }
+
+ $bp = new ilObjBookingPool($a_booking_pool, false);
+
+ foreach ($res as $index => $val) {
+ $actions = [];
+ // action assign only if user did not booked all objects.
+ //if($res[$index]['obj_count'] < ilBookingObject::getNumberOfObjectsForPool($a_booking_pool))
+
+ // alex: this does not seem to be correct: assignments are always possible for all objects
+ $has_schedule = ($bp->getScheduleType() == ilObjBookingPool::TYPE_FIX_SCHEDULE);
+ $limit_reached = (!$has_schedule && $bp->getOverallLimit() <= $val['obj_count']);
+ if (!$limit_reached) {
+ $ctrl->setParameterByClass('ilbookingparticipantgui', 'bkusr', $val['user_id']);
+ $actions[] = array(
+ 'text' => $lng->txt("book_assign_object"),
+ 'url' => $ctrl->getLinkTargetByClass("ilbookingparticipantgui", 'assignObjects')
+ );
+ $ctrl->setParameterByClass('ilbookingparticipantgui', 'bkusr', '');
+ }
+
+
+ if ($bp->getScheduleType() == ilObjBookingPool::TYPE_NO_SCHEDULE && $val['obj_count'] == 1) {
+ $ctrl->setParameterByClass('ilbookingobjectgui', 'bkusr', $val['user_id']);
+ $ctrl->setParameterByClass('ilbookingobjectgui', 'object_id', $val['object_ids'][0]);
+ $ctrl->setParameterByClass('ilbookingobjectgui', 'part_view', ilBookingParticipantGUI::PARTICIPANT_VIEW);
+
+ $actions[] = array(
+ 'text' => $lng->txt("book_deassign"),
+ 'url' => $ctrl->getLinkTargetByClass("ilbookingobjectgui", 'rsvConfirmCancelUser')
+ );
+
+ $ctrl->setParameterByClass('ilbookingparticipantgui', 'bkusr', '');
+ $ctrl->setParameterByClass('ilbookingparticipantgui', 'object_id', '');
+ $ctrl->setParameterByClass('ilbookingobjectgui', 'part_view', '');
+ } elseif ($bp->getScheduleType() == ilObjBookingPool::TYPE_FIX_SCHEDULE || $res[$index]['obj_count'] > 1) {
+ $ctrl->setParameterByClass('ilobjbookingpoolgui', 'user_id', $val['user_id']);
+ $actions[] = array(
+ 'text' => $lng->txt("book_deassign"),
+ 'url' => $ctrl->getLinkTargetByClass("ilobjbookingpoolgui", 'log')
+ );
+ $ctrl->setParameterByClass('ilobjbookingpoolgui', 'user_id', '');
+ }
+
+ //add the actions
+ $res[$index]['actions'] = $actions;
+ }
+ //echo "
"; print_r($res); exit;
+ return $res;
+ }
+
+ /**
+ * Get all participants for a booking pool.
+ * @param $a_booking_pool_id
+ * @return array
+ */
+ public static function getBookingPoolParticipants(integer $a_booking_pool_id) : array
+ {
+ global $DIC;
+ $ilDB = $DIC->database();
+ $sql = 'SELECT * FROM booking_member WHERE booking_pool_id = ' . $ilDB->quote($a_booking_pool_id, 'integer');
+
+ $set = $ilDB->query($sql);
+
+ $res = array();
+ while ($row = $ilDB->fetchAssoc($set)) {
+ $res[] = $row['user_id'];
+ }
+
+ return $res;
+ }
+
+ /**
+ *Get user data from db for an specific pool id.
+ *
+ * @param integer $a_pool_id
+ * @return array
+ */
+ public static function getUserFilter($a_pool_id)
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ $res = array();
+
+ $sql = "SELECT ud.usr_id,ud.lastname,ud.firstname,ud.login" .
+ " FROM usr_data ud " .
+ " RIGHT JOIN booking_member m ON (ud.usr_id = m.user_id)" .
+ " WHERE ud.usr_id <> " . $ilDB->quote(ANONYMOUS_USER_ID, "integer") .
+ " AND m.booking_pool_id = " . $ilDB->quote($a_pool_id, "integer") .
+ " ORDER BY ud.lastname,ud.firstname";
+
+ $set = $ilDB->query($sql);
+ while ($row = $ilDB->fetchAssoc($set)) {
+ $res[$row["usr_id"]] = $row["lastname"] . ", " . $row["firstname"] .
+ " (" . $row["login"] . ")";
+ }
+
+ return $res;
+ }
+
+ /**
+ * Returns true if the participant has a reservation for this object.
+ * @param $a_booking_object_id
+ * @param $a_participant_id
+ * @return bool
+ */
+ protected function isParticipantAssigned($a_booking_object_id, $a_participant_id)
+ {
+ if (!empty(ilBookingReservation::getObjectReservationForUser($a_booking_object_id, $a_participant_id))) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+}
diff --git a/Modules/BookingManager/classes/class.ilBookingParticipantGUI.php b/Modules/BookingManager/classes/class.ilBookingParticipantGUI.php
index 4c459a0e8854ed5e7f2996fca3b52b12041cee02..424fecba8548b82801d86bfd7fc202d115711681 100644
--- a/Modules/BookingManager/classes/class.ilBookingParticipantGUI.php
+++ b/Modules/BookingManager/classes/class.ilBookingParticipantGUI.php
@@ -12,230 +12,217 @@
*/
class ilBookingParticipantGUI
{
- /**
- * @var ilTemplate
- */
- protected $tpl;
-
- /**
- * @var ilTabsGUI
- */
- protected $tabs;
-
- /**
- * @var ilCtrl
- */
- protected $ctrl;
-
- /**
- * @var ilLanguage
- */
- protected $lng;
-
- /**
- * @var ilAccessHandler
- */
- protected $access;
-
- /**
- * @var ilToolbarGUI
- */
- protected $toolbar;
-
- const FILTER_ACTION_APPLY = 1;
- const FILTER_ACTION_RESET = 2;
-
- const PARTICIPANT_VIEW = 1;
-
- /**
- * Constructor
- * @param object $a_parent_obj
- */
- function __construct(ilObjBookingPoolGUI $a_parent_obj)
- {
- global $DIC;
-
- $this->tpl = $DIC["tpl"];
- $this->tabs = $DIC->tabs();
- $this->ctrl = $DIC->ctrl();
- $this->lng = $DIC->language();
- $this->access = $DIC->access();
- $this->toolbar = $DIC->toolbar();
-
- $this->ref_id = $a_parent_obj->ref_id;
- $this->pool_id = $a_parent_obj->object->getId();
-
- $this->lng->loadLanguageModule("book");
- }
-
- /**
- * main switch
- */
- function executeCommand()
- {
- $ilCtrl = $this->ctrl;
-
- $next_class = $ilCtrl->getNextClass($this);
-
- switch($next_class)
- {
- case 'ilrepositorysearchgui':
- include_once('./Services/Search/classes/class.ilRepositorySearchGUI.php');
- $rep_search = new ilRepositorySearchGUI();
- $ref_id = $this->ref_id;
- $rep_search->addUserAccessFilterCallable(function ($a_user_id) use ($ref_id)
- {
- return $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser(
- 'render',
- 'render',
- $this->ref_id,
- $a_user_id
- );
- });
- $rep_search->setTitle($this->lng->txt("exc_add_participant"));
- $rep_search->setCallback($this,'addParticipantObject');
- $this->ctrl->setReturn($this,'render');
- $this->ctrl->forwardCommand($rep_search);
- break;
-
- default:
- $cmd = $ilCtrl->getCmd("render");
- $this->$cmd();
- break;
- }
- return true;
- }
-
- /**
- * Render list of booking participants.
- *
- * uses ilBookingParticipantsTableGUI
- */
- function render()
- {
- if ($this->access->checkAccess('edit_permission', '', $this->ref_id))
- {
- ilRepositorySearchGUI::fillAutoCompleteToolbar(
- $this,
- $this->toolbar,
- array(
- 'auto_complete_name' => $this->lng->txt('user'),
- 'submit_name' => $this->lng->txt('add'),
- 'add_search' => true,
- 'add_from_container' => $this->ref_id
- )
- );
-
- include_once 'Modules/BookingManager/classes/class.ilBookingParticipantsTableGUI.php';
- $table = new ilBookingParticipantsTableGUI($this, 'render', $this->ref_id, $this->pool_id);
-
- $this->tpl->setContent($table->getHTML());
- }
- }
-
- /**
- * Add user as member
- */
- public function addUserFromAutoCompleteObject()
- {
- if(!strlen(trim($_POST['user_login'])))
- {
- ilUtil::sendFailure($this->lng->txt('msg_no_search_string'));
- $this->render();
- return false;
- }
-
- $users = explode(',', $_POST['user_login']);
-
- $user_ids = array();
- foreach($users as $user)
- {
- $user_id = ilObjUser::_lookupId($user);
-
- if(!$user_id)
- {
- ilUtil::sendFailure($this->lng->txt('user_not_known'));
- $this->render();
- }
- $user_ids[] = $user_id;
- }
-
- return $this->addParticipantObject($user_ids);
- }
-
- /**
- * Add new partipant
- * @param array $a_user_ids
- * @return bool
- */
- function addParticipantObject(array $a_user_ids)
- {
- foreach($a_user_ids as $user_id)
- {
- if(ilObject::_lookupType($user_id) === "usr")
- {
- require_once("./Modules/BookingManager/classes/class.ilBookingParticipant.php");
-
- $participant_obj = new ilBookingParticipant($user_id, $this->pool_id);
- if($participant_obj->getIsNew()) {
- ilUtil::sendSuccess($this->lng->txt("book_participant_assigned"),true);
- } else {
- ilUtil::sendFailure($this->lng->txt("book_participant_already_assigned"));
- return false;
- }
- }
- else
- {
- ilUtil::sendFailure("dummy error message, change me");
- return false;
- }
- }
-
- $this->ctrl->redirect($this, "render");
- return true;
- }
-
- /**
- * Apply filter from participants table gui
- */
- function applyParticipantsFilter()
- {
- $this->applyFilterAction(self::FILTER_ACTION_APPLY);
- }
-
- /**
- * Reset filter in participants table gui
- */
- function resetParticipantsFilter()
- {
- $this->applyFilterAction(self::FILTER_ACTION_RESET);
- }
-
- protected function applyFilterAction($a_filter_action)
- {
- include_once 'Modules/BookingManager/classes/class.ilBookingParticipantsTableGUI.php';
- $table = new ilBookingParticipantsTableGUI($this, 'render', $this->ref_id, $this->pool_id);
- $table->resetOffset();
- if($a_filter_action === self::FILTER_ACTION_RESET) {
- $table->resetFilter();
- } else {
- $table->writeFilterToSession();
- }
-
- $this->render();
- }
-
- function assignObjects()
- {
- $this->tabs->clearTargets();
- $this->tabs->setBackTarget($this->lng->txt('book_back_to_list'), $this->ctrl->getLinkTarget($this, 'render'));
-
- include_once("./Modules/BookingManager/classes/class.ilBookingAssignObjectsTableGUI.php");
- $table = new ilBookingAssignObjectsTableGUI($this, 'assignObjects', $this->ref_id, $this->pool_id);
-
- $this->tpl->setContent($table->getHTML());
- }
-
+ /**
+ * @var ilTemplate
+ */
+ protected $tpl;
+
+ /**
+ * @var ilTabsGUI
+ */
+ protected $tabs;
+
+ /**
+ * @var ilCtrl
+ */
+ protected $ctrl;
+
+ /**
+ * @var ilLanguage
+ */
+ protected $lng;
+
+ /**
+ * @var ilAccessHandler
+ */
+ protected $access;
+
+ /**
+ * @var ilToolbarGUI
+ */
+ protected $toolbar;
+
+ const FILTER_ACTION_APPLY = 1;
+ const FILTER_ACTION_RESET = 2;
+
+ const PARTICIPANT_VIEW = 1;
+
+ /**
+ * Constructor
+ * @param object $a_parent_obj
+ */
+ public function __construct(ilObjBookingPoolGUI $a_parent_obj)
+ {
+ global $DIC;
+
+ $this->tpl = $DIC["tpl"];
+ $this->tabs = $DIC->tabs();
+ $this->ctrl = $DIC->ctrl();
+ $this->lng = $DIC->language();
+ $this->access = $DIC->access();
+ $this->toolbar = $DIC->toolbar();
+
+ $this->ref_id = $a_parent_obj->ref_id;
+ $this->pool_id = $a_parent_obj->object->getId();
+
+ $this->lng->loadLanguageModule("book");
+ }
+
+ /**
+ * main switch
+ */
+ public function executeCommand()
+ {
+ $ilCtrl = $this->ctrl;
+
+ $next_class = $ilCtrl->getNextClass($this);
+
+ switch ($next_class) {
+ case 'ilrepositorysearchgui':
+ include_once('./Services/Search/classes/class.ilRepositorySearchGUI.php');
+ $rep_search = new ilRepositorySearchGUI();
+ $ref_id = $this->ref_id;
+ $rep_search->addUserAccessFilterCallable(function ($a_user_id) use ($ref_id) {
+ return $GLOBALS['DIC']->access()->filterUserIdsByRbacOrPositionOfCurrentUser(
+ 'render',
+ 'render',
+ $this->ref_id,
+ $a_user_id
+ );
+ });
+ $rep_search->setTitle($this->lng->txt("exc_add_participant"));
+ $rep_search->setCallback($this, 'addParticipantObject');
+ $this->ctrl->setReturn($this, 'render');
+ $this->ctrl->forwardCommand($rep_search);
+ break;
+
+ default:
+ $cmd = $ilCtrl->getCmd("render");
+ $this->$cmd();
+ break;
+ }
+ return true;
+ }
+
+ /**
+ * Render list of booking participants.
+ *
+ * uses ilBookingParticipantsTableGUI
+ */
+ public function render()
+ {
+ if ($this->access->checkAccess('edit_permission', '', $this->ref_id)) {
+ ilRepositorySearchGUI::fillAutoCompleteToolbar(
+ $this,
+ $this->toolbar,
+ array(
+ 'auto_complete_name' => $this->lng->txt('user'),
+ 'submit_name' => $this->lng->txt('add'),
+ 'add_search' => true,
+ 'add_from_container' => $this->ref_id
+ )
+ );
+
+ include_once 'Modules/BookingManager/classes/class.ilBookingParticipantsTableGUI.php';
+ $table = new ilBookingParticipantsTableGUI($this, 'render', $this->ref_id, $this->pool_id);
+
+ $this->tpl->setContent($table->getHTML());
+ }
+ }
+
+ /**
+ * Add user as member
+ */
+ public function addUserFromAutoCompleteObject()
+ {
+ if (!strlen(trim($_POST['user_login']))) {
+ ilUtil::sendFailure($this->lng->txt('msg_no_search_string'));
+ $this->render();
+ return false;
+ }
+
+ $users = explode(',', $_POST['user_login']);
+
+ $user_ids = array();
+ foreach ($users as $user) {
+ $user_id = ilObjUser::_lookupId($user);
+
+ if (!$user_id) {
+ ilUtil::sendFailure($this->lng->txt('user_not_known'));
+ $this->render();
+ }
+ $user_ids[] = $user_id;
+ }
+
+ return $this->addParticipantObject($user_ids);
+ }
+
+ /**
+ * Add new partipant
+ * @param array $a_user_ids
+ * @return bool
+ */
+ public function addParticipantObject(array $a_user_ids)
+ {
+ foreach ($a_user_ids as $user_id) {
+ if (ilObject::_lookupType($user_id) === "usr") {
+ require_once("./Modules/BookingManager/classes/class.ilBookingParticipant.php");
+
+ $participant_obj = new ilBookingParticipant($user_id, $this->pool_id);
+ if ($participant_obj->getIsNew()) {
+ ilUtil::sendSuccess($this->lng->txt("book_participant_assigned"), true);
+ } else {
+ ilUtil::sendFailure($this->lng->txt("book_participant_already_assigned"));
+ return false;
+ }
+ } else {
+ ilUtil::sendFailure("dummy error message, change me");
+ return false;
+ }
+ }
+
+ $this->ctrl->redirect($this, "render");
+ return true;
+ }
+
+ /**
+ * Apply filter from participants table gui
+ */
+ public function applyParticipantsFilter()
+ {
+ $this->applyFilterAction(self::FILTER_ACTION_APPLY);
+ }
+
+ /**
+ * Reset filter in participants table gui
+ */
+ public function resetParticipantsFilter()
+ {
+ $this->applyFilterAction(self::FILTER_ACTION_RESET);
+ }
+
+ protected function applyFilterAction($a_filter_action)
+ {
+ include_once 'Modules/BookingManager/classes/class.ilBookingParticipantsTableGUI.php';
+ $table = new ilBookingParticipantsTableGUI($this, 'render', $this->ref_id, $this->pool_id);
+ $table->resetOffset();
+ if ($a_filter_action === self::FILTER_ACTION_RESET) {
+ $table->resetFilter();
+ } else {
+ $table->writeFilterToSession();
+ }
+
+ $this->render();
+ }
+
+ public function assignObjects()
+ {
+ $this->tabs->clearTargets();
+ $this->tabs->setBackTarget($this->lng->txt('book_back_to_list'), $this->ctrl->getLinkTarget($this, 'render'));
+
+ include_once("./Modules/BookingManager/classes/class.ilBookingAssignObjectsTableGUI.php");
+ $table = new ilBookingAssignObjectsTableGUI($this, 'assignObjects', $this->ref_id, $this->pool_id);
+
+ $this->tpl->setContent($table->getHTML());
+ }
}
-
-?>
\ No newline at end of file
diff --git a/Modules/BookingManager/classes/class.ilBookingParticipantsTableGUI.php b/Modules/BookingManager/classes/class.ilBookingParticipantsTableGUI.php
index e4a0cfb66d798a9e5dabdb9abf4bfaffe7bef6a0..f02957bd7f377e220faface29f8e660c92a35a1e 100644
--- a/Modules/BookingManager/classes/class.ilBookingParticipantsTableGUI.php
+++ b/Modules/BookingManager/classes/class.ilBookingParticipantsTableGUI.php
@@ -11,171 +11,163 @@
*/
class ilBookingParticipantsTableGUI extends ilTable2GUI
{
- /**
- * @var ilAccessHandler
- */
- protected $access;
-
- /**
- * @var ilObjUser
- */
- protected $user;
-
- /**
- * @var int
- */
- protected $ref_id; // [int]
-
- /**
- * @var int
- */
- protected $pool_id; // [int]
-
- /**
- * @var
- */
- protected $filter; // [array]
-
- /**
- * @var
- */
- protected $objects; // array
-
- /**
- * Constructor
- * @param ilBookingParticipantGUI $a_parent_obj
- * @param string $a_parent_cmd
- * @param int $a_ref_id
- * @param int $a_pool_id
- */
- function __construct(ilBookingParticipantGUI $a_parent_obj, $a_parent_cmd, $a_ref_id, $a_pool_id)
- {
- global $DIC;
-
- $this->ctrl = $DIC->ctrl();
- $this->lng = $DIC->language();
- $this->user = $DIC->user();
- $this->access = $DIC->access();
- $this->ref_id = $a_ref_id;
- $this->pool_id = $a_pool_id;
-
- $this->setId("bkprt".$a_ref_id);
-
- parent::__construct($a_parent_obj, $a_parent_cmd);
-
- $this->setTitle($this->lng->txt("participants"));
-
- $this->addColumn($this->lng->txt("name"), "name");
- $this->addColumn($this->lng->txt("book_bobj"));
- $this->addColumn($this->lng->txt("action"));
-
- $this->setDefaultOrderField("name");
- $this->setDefaultOrderDirection("asc");
-
- $this->setEnableHeader(true);
- $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd));
- $this->setRowTemplate("tpl.booking_participant_row.html", "Modules/BookingManager");
- $this->setResetCommand("resetParticipantsFilter");
- $this->setFilterCommand("applyParticipantsFilter");
- $this->setDisableFilterHiding(true);
-
- $this->initFilter();
-
- $this->getItems($this->getCurrentFilter());
- }
-
- function initFilter()
- {
- //object
- $this->objects = array();
- foreach(ilBookingObject::getList($this->pool_id) as $item)
- {
- $this->objects[$item["booking_object_id"]] = $item["title"];
- }
- $item = $this->addFilterItemByMetaType("object", ilTable2GUI::FILTER_SELECT);
- $item->setOptions(array(""=>$this->lng->txt('book_all'))+$this->objects);
- $this->filter["object"] = $item->getValue();
-
- $title = $this->addFilterItemByMetaType(
- "title",
- ilTable2GUI::FILTER_TEXT,
- false,
- $this->lng->txt("object")." ".$this->lng->txt("title")."/".$this->lng->txt("description")
- );
- $this->filter["title"] = $title->getValue();
-
- //user
- require_once("./Modules/BookingManager/classes/class.ilBookingParticipant.php");
- $options = array(""=>$this->lng->txt('book_all'))+
- ilBookingParticipant::getUserFilter($this->pool_id);
- $item = $this->addFilterItemByMetaType("user", ilTable2GUI::FILTER_SELECT);
- $item->setOptions($options);
- $this->filter["user_id"] = $item->getValue();
- }
-
- /**
- * Get current filter settings
- * @return array
- */
- function getCurrentFilter()
- {
- $filter = array();
- if($this->filter["object"])
- {
- $filter["object"] = $this->filter["object"];
- }
- if($this->filter["title"])
- {
- $filter["title"] = $this->filter["title"];
- }
- if($this->filter["user_id"])
- {
- $filter["user_id"] = $this->filter["user_id"];
- }
-
- return $filter;
- }
-
- /**
- * Gather data and build rows
- * @param array $filter
- */
- function getItems(array $filter)
- {
- include_once "Modules/BookingManager/classes/class.ilBookingParticipant.php";
-
- if($filter["object"]) {
- $data = ilBookingParticipant::getList($this->pool_id, $filter, $filter["object"]);
- } else {
- $data = ilBookingParticipant::getList($this->pool_id, $filter);
- }
-
- $this->setMaxCount(sizeof($data));
- $this->setData($data);
- }
-
- /**
- * Fill table row
- * @param array $a_set
- */
- protected function fillRow($a_set)
- {
- $this->tpl->setVariable("TXT_NAME", $a_set['name']);
- $this->tpl->setCurrentBlock('object_titles');
- foreach($a_set['object_title'] as $obj_title)
- {
- $this->tpl->setVariable("TXT_OBJECT", $obj_title);
- $this->tpl->parseCurrentBlock();
- }
-
- $this->tpl->setCurrentBlock('actions');
- foreach($a_set['actions'] as $key => $action)
- {
- $this->tpl->setVariable("TXT_ACTION", $action['text']);
- $this->tpl->setVariable("URL_ACTION", $action['url']);
- $this->tpl->parseCurrentBlock();
- }
- }
+ /**
+ * @var ilAccessHandler
+ */
+ protected $access;
+
+ /**
+ * @var ilObjUser
+ */
+ protected $user;
+
+ /**
+ * @var int
+ */
+ protected $ref_id; // [int]
+
+ /**
+ * @var int
+ */
+ protected $pool_id; // [int]
+
+ /**
+ * @var
+ */
+ protected $filter; // [array]
+
+ /**
+ * @var
+ */
+ protected $objects; // array
+
+ /**
+ * Constructor
+ * @param ilBookingParticipantGUI $a_parent_obj
+ * @param string $a_parent_cmd
+ * @param int $a_ref_id
+ * @param int $a_pool_id
+ */
+ public function __construct(ilBookingParticipantGUI $a_parent_obj, $a_parent_cmd, $a_ref_id, $a_pool_id)
+ {
+ global $DIC;
+
+ $this->ctrl = $DIC->ctrl();
+ $this->lng = $DIC->language();
+ $this->user = $DIC->user();
+ $this->access = $DIC->access();
+ $this->ref_id = $a_ref_id;
+ $this->pool_id = $a_pool_id;
+
+ $this->setId("bkprt" . $a_ref_id);
+
+ parent::__construct($a_parent_obj, $a_parent_cmd);
+
+ $this->setTitle($this->lng->txt("participants"));
+
+ $this->addColumn($this->lng->txt("name"), "name");
+ $this->addColumn($this->lng->txt("book_bobj"));
+ $this->addColumn($this->lng->txt("action"));
+
+ $this->setDefaultOrderField("name");
+ $this->setDefaultOrderDirection("asc");
+
+ $this->setEnableHeader(true);
+ $this->setFormAction($this->ctrl->getFormAction($a_parent_obj, $a_parent_cmd));
+ $this->setRowTemplate("tpl.booking_participant_row.html", "Modules/BookingManager");
+ $this->setResetCommand("resetParticipantsFilter");
+ $this->setFilterCommand("applyParticipantsFilter");
+ $this->setDisableFilterHiding(true);
+
+ $this->initFilter();
+
+ $this->getItems($this->getCurrentFilter());
+ }
+
+ public function initFilter()
+ {
+ //object
+ $this->objects = array();
+ foreach (ilBookingObject::getList($this->pool_id) as $item) {
+ $this->objects[$item["booking_object_id"]] = $item["title"];
+ }
+ $item = $this->addFilterItemByMetaType("object", ilTable2GUI::FILTER_SELECT);
+ $item->setOptions(array(""=>$this->lng->txt('book_all'))+$this->objects);
+ $this->filter["object"] = $item->getValue();
+
+ $title = $this->addFilterItemByMetaType(
+ "title",
+ ilTable2GUI::FILTER_TEXT,
+ false,
+ $this->lng->txt("object") . " " . $this->lng->txt("title") . "/" . $this->lng->txt("description")
+ );
+ $this->filter["title"] = $title->getValue();
+
+ //user
+ require_once("./Modules/BookingManager/classes/class.ilBookingParticipant.php");
+ $options = array(""=>$this->lng->txt('book_all'))+
+ ilBookingParticipant::getUserFilter($this->pool_id);
+ $item = $this->addFilterItemByMetaType("user", ilTable2GUI::FILTER_SELECT);
+ $item->setOptions($options);
+ $this->filter["user_id"] = $item->getValue();
+ }
+
+ /**
+ * Get current filter settings
+ * @return array
+ */
+ public function getCurrentFilter()
+ {
+ $filter = array();
+ if ($this->filter["object"]) {
+ $filter["object"] = $this->filter["object"];
+ }
+ if ($this->filter["title"]) {
+ $filter["title"] = $this->filter["title"];
+ }
+ if ($this->filter["user_id"]) {
+ $filter["user_id"] = $this->filter["user_id"];
+ }
+
+ return $filter;
+ }
+
+ /**
+ * Gather data and build rows
+ * @param array $filter
+ */
+ public function getItems(array $filter)
+ {
+ include_once "Modules/BookingManager/classes/class.ilBookingParticipant.php";
+
+ if ($filter["object"]) {
+ $data = ilBookingParticipant::getList($this->pool_id, $filter, $filter["object"]);
+ } else {
+ $data = ilBookingParticipant::getList($this->pool_id, $filter);
+ }
+
+ $this->setMaxCount(sizeof($data));
+ $this->setData($data);
+ }
+
+ /**
+ * Fill table row
+ * @param array $a_set
+ */
+ protected function fillRow($a_set)
+ {
+ $this->tpl->setVariable("TXT_NAME", $a_set['name']);
+ $this->tpl->setCurrentBlock('object_titles');
+ foreach ($a_set['object_title'] as $obj_title) {
+ $this->tpl->setVariable("TXT_OBJECT", $obj_title);
+ $this->tpl->parseCurrentBlock();
+ }
+
+ $this->tpl->setCurrentBlock('actions');
+ foreach ($a_set['actions'] as $key => $action) {
+ $this->tpl->setVariable("TXT_ACTION", $action['text']);
+ $this->tpl->setVariable("URL_ACTION", $action['url']);
+ $this->tpl->parseCurrentBlock();
+ }
+ }
}
-
-?>
\ No newline at end of file
diff --git a/Modules/BookingManager/classes/class.ilBookingReservation.php b/Modules/BookingManager/classes/class.ilBookingReservation.php
index ddab0b43e206f960eedc9d2b8a25d2d849cf4209..27b2d0f9f0092fed7ccb2d48346860137d1eda64 100644
--- a/Modules/BookingManager/classes/class.ilBookingReservation.php
+++ b/Modules/BookingManager/classes/class.ilBookingReservation.php
@@ -11,1189 +11,1115 @@
*/
class ilBookingReservation
{
- /**
- * @var ilDB
- */
- protected $db;
-
- protected $id; // int
- protected $object_id; // int
- protected $user_id; // int
- protected $from; // timestamp
- protected $to; // timestamp
- protected $status; // status
- protected $group_id; // int
- protected $assigner_id; // int
-
- const STATUS_IN_USE = 2;
- const STATUS_CANCELLED = 5;
-
- /**
- * Constructor
- *
- * if id is given will read dataset from db
- *
- * @param int $a_id
- */
- function __construct($a_id = NULL)
- {
- global $DIC;
-
- $this->db = $DIC->database();
- $this->id = (int)$a_id;
- $this->read();
- }
-
- /**
- * Get id
- * @return int
- */
- function getId()
- {
- return $this->id;
- }
-
- /**
- * Set object id
- * @param int $a_object_id
- */
- function setObjectId($a_object_id)
- {
- $this->object_id = $a_object_id;
- }
-
- /**
- * Get object id
- * @return int
- */
- function getObjectId()
- {
- return $this->object_id;
- }
-
- /**
- * Set booking user id
- * @param int $a_user_id
- */
- function setUserId($a_user_id)
- {
- $this->user_id = (int)$a_user_id;
- }
-
- /**
- * Get booking user id
- * @return int
- */
- function getUserId()
- {
- return $this->user_id;
- }
-
- /**
- * Set assigner user id
- * @param $a_assigner_id
- */
- function setAssignerId($a_assigner_id)
- {
- $this->assigner_id = (int)$a_assigner_id;
- }
-
- /**
- * Get assigner user id
- * @return int
- */
- function getAssignerId()
- {
- return $this->assigner_id;
- }
-
- /**
- * Set booking from date
- * @param int $a_from
- */
- function setFrom($a_from)
- {
- $this->from = (int)$a_from;
- }
-
- /**
- * Get booking from date
- * @return int
- */
- function getFrom()
- {
- return $this->from;
- }
-
- /**
- * Set booking to date
- * @param int $a_to
- */
- function setTo($a_to)
- {
- $this->to = (int)$a_to;
- }
-
- /**
- * Get booking to date
- * @return int
- */
- function getTo()
- {
- return $this->to;
- }
-
- /**
- * Set booking status
- * @param int $a_status
- */
- function setStatus($a_status)
- {
- if($a_status === NULL)
- {
- $this->status = NULL;
- }
- if($this->isValidStatus((int)$a_status))
- {
- $this->status = (int)$a_status;
- }
- }
-
- /**
- * Get booking status
- * @return int
- */
- function getStatus()
- {
- return $this->status;
- }
-
- /**
- * Check if given status is valid
- * @param int $a_status
- * @return bool
- */
- static function isValidStatus($a_status)
- {
- if(in_array($a_status, array(self::STATUS_IN_USE, self::STATUS_CANCELLED)))
- {
- return true;
- }
- return false;
- }
-
- /**
- * Set group id
- * @param int $a_group_id
- */
- function setGroupId($a_group_id)
- {
- $this->group_id = $a_group_id;
- }
-
- /**
- * Get group id
- * @return int
- */
- function getGroupId()
- {
- return $this->group_id;
- }
-
- /**
- * Get dataset from db
- */
- protected function read()
- {
- $ilDB = $this->db;
-
- if($this->id)
- {
- $set = $ilDB->query('SELECT *'.
- ' FROM booking_reservation'.
- ' WHERE booking_reservation_id = '.$ilDB->quote($this->id, 'integer'));
- $row = $ilDB->fetchAssoc($set);
- $this->setUserId($row['user_id']);
- $this->setAssignerId($row['assigner_id']);
- $this->setObjectId($row['object_id']);
- $this->setFrom($row['date_from']);
- $this->setTo($row['date_to']);
- $this->setStatus($row['status']);
- $this->setGroupId($row['group_id']);
- }
- }
-
- /**
- * Create new entry in db
- * @return bool
- */
- function save()
- {
- $ilDB = $this->db;
-
- if($this->id)
- {
- return false;
- }
-
- $this->id = $ilDB->nextId('booking_reservation');
-
- return $ilDB->manipulate('INSERT INTO booking_reservation'.
- ' (booking_reservation_id,user_id,assigner_id,object_id,date_from,date_to,status,group_id)'.
- ' VALUES ('.$ilDB->quote($this->id, 'integer').
- ','.$ilDB->quote($this->getUserId(), 'integer').
- ','.$ilDB->quote($this->getAssignerId(), 'integer').
- ','.$ilDB->quote($this->getObjectId(), 'integer').
- ','.$ilDB->quote($this->getFrom(), 'integer').
- ','.$ilDB->quote($this->getTo(), 'integer').
- ','.$ilDB->quote($this->getStatus(), 'integer').
- ','.$ilDB->quote($this->getGroupId(), 'integer').')');
- }
-
- /**
- * Update entry in db
- * @return bool
- */
- function update()
- {
- $ilDB = $this->db;
-
- if(!$this->id)
- {
- return false;
- }
-
- /* there can only be 1
- if($this->getStatus() == self::STATUS_IN_USE)
- {
- $ilDB->manipulate('UPDATE booking_reservation'.
- ' SET status = '.$ilDB->quote(NULL, 'integer').
- ' WHERE object_id = '.$ilDB->quote($this->getObjectId(), 'integer').
- ' AND status = '.$ilDB->quote(self::STATUS_IN_USE, 'integer'));
- }
- */
-
- return $ilDB->manipulate('UPDATE booking_reservation'.
- ' SET object_id = '.$ilDB->quote($this->getObjectId(), 'text').
- ', user_id = '.$ilDB->quote($this->getUserId(), 'integer').
- ', assigner_id = '.$ilDB->quote($this->getAssignerId(), 'integer').
- ', date_from = '.$ilDB->quote($this->getFrom(), 'integer').
- ', date_to = '.$ilDB->quote($this->getTo(), 'integer').
- ', status = '.$ilDB->quote($this->getStatus(), 'integer').
- ', group_id = '.$ilDB->quote($this->getGroupId(), 'integer').
- ' WHERE booking_reservation_id = '.$ilDB->quote($this->id, 'integer'));
- }
-
- /**
- * Delete single entry
- * @return bool
- */
- function delete()
- {
- $ilDB = $this->db;
-
- if($this->id)
- {
- return $ilDB->manipulate('DELETE FROM booking_reservation'.
- ' WHERE booking_reservation_id = '.$ilDB->quote($this->id, 'integer'));
- }
- }
-
- /**
- * Get next group id
- * @return int
- */
- public static function getNewGroupId()
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- return $ilDB->nextId('booking_reservation_group');
- }
-
- /**
- * Check if any of given objects are bookable
- * @param array $a_ids
- * @param int $a_from
- * @param int $a_to
- * @param int $a_return_single
- * @return int
- */
- static function getAvailableObject(array $a_ids, $a_from, $a_to, $a_return_single = true, $a_return_counter = false)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $nr_map = ilBookingObject::getNrOfItemsForObjects($a_ids);
-
- $from = $ilDB->quote($a_from, 'integer');
- $to = $ilDB->quote($a_to, 'integer');
-
- $set = $ilDB->query('SELECT count(*) cnt, object_id'.
- ' FROM booking_reservation'.
- ' WHERE '.$ilDB->in('object_id', $a_ids, '', 'integer').
- ' AND (status IS NULL OR status <> '.$ilDB->quote(self::STATUS_CANCELLED, 'integer').')'.
- ' AND ((date_from <= '.$from.' AND date_to >= '.$from.')'.
- ' OR (date_from <= '.$to.' AND date_to >= '.$to.')'.
- ' OR (date_from >= '.$from.' AND date_to <= '.$to.'))'.
- ' GROUP BY object_id');
- $blocked = $counter = array();
- while($row = $ilDB->fetchAssoc($set))
- {
- if($row['cnt'] >= $nr_map[$row['object_id']])
- {
- $blocked[] = $row['object_id'];
- }
- else if($a_return_counter)
- {
- $counter[$row['object_id']] = (int)$nr_map[$row['object_id']]-(int)$row['cnt'];
- }
- }
-
- // #17868 - validate against schedule availability
- foreach($a_ids as $obj_id)
- {
- $bobj = new ilBookingObject($obj_id);
- if($bobj->getScheduleId())
- {
- include_once "Modules/BookingManager/classes/class.ilBookingSchedule.php";
- $schedule = new ilBookingSchedule($bobj->getScheduleId());
-
- $av_from = ($schedule->getAvailabilityFrom() && !$schedule->getAvailabilityFrom()->isNull())
- ? $schedule->getAvailabilityFrom()->get(IL_CAL_UNIX)
- : null;
- $av_to = ($schedule->getAvailabilityTo() && !$schedule->getAvailabilityTo()->isNull())
- ? strtotime($schedule->getAvailabilityTo()->get(IL_CAL_DATE)." 23:59:59")
- : null;
-
- if(($av_from && $a_from < $av_from) ||
- ($av_to && $a_to > $av_to))
- {
- $blocked[] = $obj_id;
- unset($counter[$obj_id]);
- }
- }
- }
-
- $available = array_diff($a_ids, $blocked);
- if(sizeof($available))
- {
- if($a_return_counter)
- {
- foreach($a_ids as $id)
- {
- if(!isset($counter[$id]))
- {
- $counter[$id] = (int)$nr_map[$id];
- }
- }
- return $counter;
- }
- else if($a_return_single)
- {
- return array_shift($available);
- }
- else
- {
- return $available;
- }
- }
- }
-
- static function isObjectAvailableInPeriod($a_obj_id, ilBookingSchedule $a_schedule, $a_from, $a_to)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- if(!$a_from)
- {
- $a_from = time();
- }
- if(!$a_to)
- {
- $a_to = strtotime("+1year", $a_from);
- }
-
- if($a_from > $a_to)
- {
- return;
- }
-
- $from = $ilDB->quote($a_from, 'integer');
- $to = $ilDB->quote($a_to, 'integer');
-
- // all bookings in period
- $now = time();
- $set = $ilDB->query('SELECT count(*) cnt'.
- ' FROM booking_reservation'.
- ' WHERE object_id = '.$ilDB->quote($a_obj_id, 'integer').
- ' AND (status IS NULL OR status <> '.$ilDB->quote(self::STATUS_CANCELLED, 'integer').')'.
- ' AND date_to > '.$now.
- ' AND ((date_from <= '.$from.' AND date_to >= '.$from.')'.
- ' OR (date_from <= '.$to.' AND date_to >= '.$to.')'.
- ' OR (date_from >= '.$from.' AND date_to <= '.$to.'))');
- $row = $ilDB->fetchAssoc($set);
- $booked_in_period = $row["cnt"];
-
- $per_slot = ilBookingObject::getNrOfItemsForObjects(array($a_obj_id));
- $per_slot = $per_slot[$a_obj_id];
-
- // max available nr of items per (week)day
- $schedule_slots = array();
- $definition = $a_schedule->getDefinition();
- $map = array_flip(array("su", "mo", "tu", "we", "th", "fr", "sa"));
- foreach($definition as $day => $day_slots)
- {
- $schedule_slots[$map[$day]] = $day_slots;
- }
-
- $av_from = ($a_schedule->getAvailabilityFrom() && !$a_schedule->getAvailabilityFrom()->isNull())
- ? $a_schedule->getAvailabilityFrom()->get(IL_CAL_UNIX)
- : null;
- $av_to = ($a_schedule->getAvailabilityTo() && !$a_schedule->getAvailabilityTo()->isNull())
- ? strtotime($a_schedule->getAvailabilityTo()->get(IL_CAL_DATE)." 23:59:59")
- : null;
-
- // sum up max available items in period per (week)day
- $available_in_period = 0;
- $loop = 0;
- while($a_from < $a_to &&
- ++$loop < 1000)
- {
- // any slots for current weekday?
- $day_slots = $schedule_slots[date("w", $a_from)];
- if($day_slots)
- {
- foreach($day_slots as $slot)
- {
- // convert slot to current datetime
- $slot = explode("-", $slot);
- $slot_from = strtotime(date("Y-m-d", $a_from)." ".$slot[0]);
- $slot_to = strtotime(date("Y-m-d", $a_from)." ".$slot[1]);
-
- // slot has to be in the future and part of schedule availability
- if($slot_to > time() &&
- $slot_from >= $av_from &&
- $slot_to <= $av_to)
- {
- $available_in_period += $per_slot;
- }
- }
- }
-
- $a_from += (60*60*24);
- }
-
- if($available_in_period - $booked_in_period > 0) {
- return true;
- }
-
- return false;
- }
-
- //check if the user reached the limit of bookings in this booking pool.
- static function isBookingPoolLimitReachedByUser(int $a_user_id, int $a_pool_id): int
- {
- global $DIC;
- $ilDB = $DIC->database();
-
- $booking_pool_objects = ilBookingObject::getObjectsForPool($a_pool_id);
-
- $query = "SELECT count(user_id) total".
- " FROM booking_reservation".
- " WHERE ".$ilDB->in('object_id', $booking_pool_objects,false,'integer').
- " AND user_id = ".$a_user_id.
- " AND (status IS NULL OR status <> ".ilBookingReservation::STATUS_CANCELLED.')';
- $res = $ilDB->query($query);
- $row = $res->fetchRow(ilDBConstants::FETCHMODE_ASSOC);
-
- return (int) $row['total'];
- }
-
- static function getMembersWithoutReservation(int $a_object_id): array
- {
- global $DIC;
- $ilDB = $DIC->database();
+ /**
+ * @var ilDB
+ */
+ protected $db;
+
+ protected $id; // int
+ protected $object_id; // int
+ protected $user_id; // int
+ protected $from; // timestamp
+ protected $to; // timestamp
+ protected $status; // status
+ protected $group_id; // int
+ protected $assigner_id; // int
+
+ const STATUS_IN_USE = 2;
+ const STATUS_CANCELLED = 5;
+
+ /**
+ * Constructor
+ *
+ * if id is given will read dataset from db
+ *
+ * @param int $a_id
+ */
+ public function __construct($a_id = null)
+ {
+ global $DIC;
+
+ $this->db = $DIC->database();
+ $this->id = (int) $a_id;
+ $this->read();
+ }
+
+ /**
+ * Get id
+ * @return int
+ */
+ public function getId()
+ {
+ return $this->id;
+ }
+
+ /**
+ * Set object id
+ * @param int $a_object_id
+ */
+ public function setObjectId($a_object_id)
+ {
+ $this->object_id = $a_object_id;
+ }
+
+ /**
+ * Get object id
+ * @return int
+ */
+ public function getObjectId()
+ {
+ return $this->object_id;
+ }
+
+ /**
+ * Set booking user id
+ * @param int $a_user_id
+ */
+ public function setUserId($a_user_id)
+ {
+ $this->user_id = (int) $a_user_id;
+ }
+
+ /**
+ * Get booking user id
+ * @return int
+ */
+ public function getUserId()
+ {
+ return $this->user_id;
+ }
+
+ /**
+ * Set assigner user id
+ * @param $a_assigner_id
+ */
+ public function setAssignerId($a_assigner_id)
+ {
+ $this->assigner_id = (int) $a_assigner_id;
+ }
+
+ /**
+ * Get assigner user id
+ * @return int
+ */
+ public function getAssignerId()
+ {
+ return $this->assigner_id;
+ }
+
+ /**
+ * Set booking from date
+ * @param int $a_from
+ */
+ public function setFrom($a_from)
+ {
+ $this->from = (int) $a_from;
+ }
+
+ /**
+ * Get booking from date
+ * @return int
+ */
+ public function getFrom()
+ {
+ return $this->from;
+ }
+
+ /**
+ * Set booking to date
+ * @param int $a_to
+ */
+ public function setTo($a_to)
+ {
+ $this->to = (int) $a_to;
+ }
+
+ /**
+ * Get booking to date
+ * @return int
+ */
+ public function getTo()
+ {
+ return $this->to;
+ }
+
+ /**
+ * Set booking status
+ * @param int $a_status
+ */
+ public function setStatus($a_status)
+ {
+ if ($a_status === null) {
+ $this->status = null;
+ }
+ if ($this->isValidStatus((int) $a_status)) {
+ $this->status = (int) $a_status;
+ }
+ }
+
+ /**
+ * Get booking status
+ * @return int
+ */
+ public function getStatus()
+ {
+ return $this->status;
+ }
+
+ /**
+ * Check if given status is valid
+ * @param int $a_status
+ * @return bool
+ */
+ public static function isValidStatus($a_status)
+ {
+ if (in_array($a_status, array(self::STATUS_IN_USE, self::STATUS_CANCELLED))) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Set group id
+ * @param int $a_group_id
+ */
+ public function setGroupId($a_group_id)
+ {
+ $this->group_id = $a_group_id;
+ }
+
+ /**
+ * Get group id
+ * @return int
+ */
+ public function getGroupId()
+ {
+ return $this->group_id;
+ }
+
+ /**
+ * Get dataset from db
+ */
+ protected function read()
+ {
+ $ilDB = $this->db;
+
+ if ($this->id) {
+ $set = $ilDB->query('SELECT *' .
+ ' FROM booking_reservation' .
+ ' WHERE booking_reservation_id = ' . $ilDB->quote($this->id, 'integer'));
+ $row = $ilDB->fetchAssoc($set);
+ $this->setUserId($row['user_id']);
+ $this->setAssignerId($row['assigner_id']);
+ $this->setObjectId($row['object_id']);
+ $this->setFrom($row['date_from']);
+ $this->setTo($row['date_to']);
+ $this->setStatus($row['status']);
+ $this->setGroupId($row['group_id']);
+ }
+ }
+
+ /**
+ * Create new entry in db
+ * @return bool
+ */
+ public function save()
+ {
+ $ilDB = $this->db;
+
+ if ($this->id) {
+ return false;
+ }
+
+ $this->id = $ilDB->nextId('booking_reservation');
+
+ return $ilDB->manipulate('INSERT INTO booking_reservation' .
+ ' (booking_reservation_id,user_id,assigner_id,object_id,date_from,date_to,status,group_id)' .
+ ' VALUES (' . $ilDB->quote($this->id, 'integer') .
+ ',' . $ilDB->quote($this->getUserId(), 'integer') .
+ ',' . $ilDB->quote($this->getAssignerId(), 'integer') .
+ ',' . $ilDB->quote($this->getObjectId(), 'integer') .
+ ',' . $ilDB->quote($this->getFrom(), 'integer') .
+ ',' . $ilDB->quote($this->getTo(), 'integer') .
+ ',' . $ilDB->quote($this->getStatus(), 'integer') .
+ ',' . $ilDB->quote($this->getGroupId(), 'integer') . ')');
+ }
+
+ /**
+ * Update entry in db
+ * @return bool
+ */
+ public function update()
+ {
+ $ilDB = $this->db;
+
+ if (!$this->id) {
+ return false;
+ }
+
+ /* there can only be 1
+ if($this->getStatus() == self::STATUS_IN_USE)
+ {
+ $ilDB->manipulate('UPDATE booking_reservation'.
+ ' SET status = '.$ilDB->quote(NULL, 'integer').
+ ' WHERE object_id = '.$ilDB->quote($this->getObjectId(), 'integer').
+ ' AND status = '.$ilDB->quote(self::STATUS_IN_USE, 'integer'));
+ }
+ */
+
+ return $ilDB->manipulate('UPDATE booking_reservation' .
+ ' SET object_id = ' . $ilDB->quote($this->getObjectId(), 'text') .
+ ', user_id = ' . $ilDB->quote($this->getUserId(), 'integer') .
+ ', assigner_id = ' . $ilDB->quote($this->getAssignerId(), 'integer') .
+ ', date_from = ' . $ilDB->quote($this->getFrom(), 'integer') .
+ ', date_to = ' . $ilDB->quote($this->getTo(), 'integer') .
+ ', status = ' . $ilDB->quote($this->getStatus(), 'integer') .
+ ', group_id = ' . $ilDB->quote($this->getGroupId(), 'integer') .
+ ' WHERE booking_reservation_id = ' . $ilDB->quote($this->id, 'integer'));
+ }
+
+ /**
+ * Delete single entry
+ * @return bool
+ */
+ public function delete()
+ {
+ $ilDB = $this->db;
+
+ if ($this->id) {
+ return $ilDB->manipulate('DELETE FROM booking_reservation' .
+ ' WHERE booking_reservation_id = ' . $ilDB->quote($this->id, 'integer'));
+ }
+ }
+
+ /**
+ * Get next group id
+ * @return int
+ */
+ public static function getNewGroupId()
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ return $ilDB->nextId('booking_reservation_group');
+ }
+
+ /**
+ * Check if any of given objects are bookable
+ * @param array $a_ids
+ * @param int $a_from
+ * @param int $a_to
+ * @param int $a_return_single
+ * @return int
+ */
+ public static function getAvailableObject(array $a_ids, $a_from, $a_to, $a_return_single = true, $a_return_counter = false)
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ $nr_map = ilBookingObject::getNrOfItemsForObjects($a_ids);
+
+ $from = $ilDB->quote($a_from, 'integer');
+ $to = $ilDB->quote($a_to, 'integer');
+
+ $set = $ilDB->query('SELECT count(*) cnt, object_id' .
+ ' FROM booking_reservation' .
+ ' WHERE ' . $ilDB->in('object_id', $a_ids, '', 'integer') .
+ ' AND (status IS NULL OR status <> ' . $ilDB->quote(self::STATUS_CANCELLED, 'integer') . ')' .
+ ' AND ((date_from <= ' . $from . ' AND date_to >= ' . $from . ')' .
+ ' OR (date_from <= ' . $to . ' AND date_to >= ' . $to . ')' .
+ ' OR (date_from >= ' . $from . ' AND date_to <= ' . $to . '))' .
+ ' GROUP BY object_id');
+ $blocked = $counter = array();
+ while ($row = $ilDB->fetchAssoc($set)) {
+ if ($row['cnt'] >= $nr_map[$row['object_id']]) {
+ $blocked[] = $row['object_id'];
+ } elseif ($a_return_counter) {
+ $counter[$row['object_id']] = (int) $nr_map[$row['object_id']]-(int) $row['cnt'];
+ }
+ }
+
+ // #17868 - validate against schedule availability
+ foreach ($a_ids as $obj_id) {
+ $bobj = new ilBookingObject($obj_id);
+ if ($bobj->getScheduleId()) {
+ include_once "Modules/BookingManager/classes/class.ilBookingSchedule.php";
+ $schedule = new ilBookingSchedule($bobj->getScheduleId());
+
+ $av_from = ($schedule->getAvailabilityFrom() && !$schedule->getAvailabilityFrom()->isNull())
+ ? $schedule->getAvailabilityFrom()->get(IL_CAL_UNIX)
+ : null;
+ $av_to = ($schedule->getAvailabilityTo() && !$schedule->getAvailabilityTo()->isNull())
+ ? strtotime($schedule->getAvailabilityTo()->get(IL_CAL_DATE) . " 23:59:59")
+ : null;
+
+ if (($av_from && $a_from < $av_from) ||
+ ($av_to && $a_to > $av_to)) {
+ $blocked[] = $obj_id;
+ unset($counter[$obj_id]);
+ }
+ }
+ }
+
+ $available = array_diff($a_ids, $blocked);
+ if (sizeof($available)) {
+ if ($a_return_counter) {
+ foreach ($a_ids as $id) {
+ if (!isset($counter[$id])) {
+ $counter[$id] = (int) $nr_map[$id];
+ }
+ }
+ return $counter;
+ } elseif ($a_return_single) {
+ return array_shift($available);
+ } else {
+ return $available;
+ }
+ }
+ }
+
+ public static function isObjectAvailableInPeriod($a_obj_id, ilBookingSchedule $a_schedule, $a_from, $a_to)
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ if (!$a_from) {
+ $a_from = time();
+ }
+ if (!$a_to) {
+ $a_to = strtotime("+1year", $a_from);
+ }
+
+ if ($a_from > $a_to) {
+ return;
+ }
+
+ $from = $ilDB->quote($a_from, 'integer');
+ $to = $ilDB->quote($a_to, 'integer');
+
+ // all bookings in period
+ $now = time();
+ $set = $ilDB->query('SELECT count(*) cnt' .
+ ' FROM booking_reservation' .
+ ' WHERE object_id = ' . $ilDB->quote($a_obj_id, 'integer') .
+ ' AND (status IS NULL OR status <> ' . $ilDB->quote(self::STATUS_CANCELLED, 'integer') . ')' .
+ ' AND date_to > ' . $now .
+ ' AND ((date_from <= ' . $from . ' AND date_to >= ' . $from . ')' .
+ ' OR (date_from <= ' . $to . ' AND date_to >= ' . $to . ')' .
+ ' OR (date_from >= ' . $from . ' AND date_to <= ' . $to . '))');
+ $row = $ilDB->fetchAssoc($set);
+ $booked_in_period = $row["cnt"];
+
+ $per_slot = ilBookingObject::getNrOfItemsForObjects(array($a_obj_id));
+ $per_slot = $per_slot[$a_obj_id];
+
+ // max available nr of items per (week)day
+ $schedule_slots = array();
+ $definition = $a_schedule->getDefinition();
+ $map = array_flip(array("su", "mo", "tu", "we", "th", "fr", "sa"));
+ foreach ($definition as $day => $day_slots) {
+ $schedule_slots[$map[$day]] = $day_slots;
+ }
+
+ $av_from = ($a_schedule->getAvailabilityFrom() && !$a_schedule->getAvailabilityFrom()->isNull())
+ ? $a_schedule->getAvailabilityFrom()->get(IL_CAL_UNIX)
+ : null;
+ $av_to = ($a_schedule->getAvailabilityTo() && !$a_schedule->getAvailabilityTo()->isNull())
+ ? strtotime($a_schedule->getAvailabilityTo()->get(IL_CAL_DATE) . " 23:59:59")
+ : null;
+
+ // sum up max available items in period per (week)day
+ $available_in_period = 0;
+ $loop = 0;
+ while ($a_from < $a_to &&
+ ++$loop < 1000) {
+ // any slots for current weekday?
+ $day_slots = $schedule_slots[date("w", $a_from)];
+ if ($day_slots) {
+ foreach ($day_slots as $slot) {
+ // convert slot to current datetime
+ $slot = explode("-", $slot);
+ $slot_from = strtotime(date("Y-m-d", $a_from) . " " . $slot[0]);
+ $slot_to = strtotime(date("Y-m-d", $a_from) . " " . $slot[1]);
+
+ // slot has to be in the future and part of schedule availability
+ if ($slot_to > time() &&
+ $slot_from >= $av_from &&
+ $slot_to <= $av_to) {
+ $available_in_period += $per_slot;
+ }
+ }
+ }
+
+ $a_from += (60*60*24);
+ }
+
+ if ($available_in_period - $booked_in_period > 0) {
+ return true;
+ }
+
+ return false;
+ }
+
+ //check if the user reached the limit of bookings in this booking pool.
+ public static function isBookingPoolLimitReachedByUser(int $a_user_id, int $a_pool_id) : int
+ {
+ global $DIC;
+ $ilDB = $DIC->database();
+
+ $booking_pool_objects = ilBookingObject::getObjectsForPool($a_pool_id);
+
+ $query = "SELECT count(user_id) total" .
+ " FROM booking_reservation" .
+ " WHERE " . $ilDB->in('object_id', $booking_pool_objects, false, 'integer') .
+ " AND user_id = " . $a_user_id .
+ " AND (status IS NULL OR status <> " . ilBookingReservation::STATUS_CANCELLED . ')';
+ $res = $ilDB->query($query);
+ $row = $res->fetchRow(ilDBConstants::FETCHMODE_ASSOC);
+
+ return (int) $row['total'];
+ }
+
+ public static function getMembersWithoutReservation(int $a_object_id) : array
+ {
+ global $DIC;
+ $ilDB = $DIC->database();
$pool_id = ilBookingObject::lookupPoolId($a_object_id);
- $res = array();
- $query = 'SELECT DISTINCT bm.user_id user_id'.
- ' FROM booking_member bm'.
- ' WHERE bm.booking_pool_id = '.$ilDB->quote($pool_id, 'integer').
- ' AND bm.user_id NOT IN ('.
- 'SELECT user_id'.
- ' FROM booking_reservation'.
- ' WHERE object_id = '.$ilDB->quote($a_object_id, 'integer').
- ' AND (status IS NULL OR status <> '.ilBookingReservation::STATUS_CANCELLED.'))';
-
- $set = $ilDB->query($query);
-
- while($row = $ilDB->fetchAssoc($set))
- {
- $res[] = $row['user_id'];
- }
-
- return $res;
- }
-
- static function isObjectAvailableNoSchedule($a_obj_id)
- {
- $available = self::getNumAvailablesNoSchedule($a_obj_id);
- return (bool)$available; // #11864
- }
- static function numAvailableFromObjectNoSchedule($a_obj_id)
- {
- $available = self::getNumAvailablesNoSchedule($a_obj_id);
- return (int)$available;
- }
-
- public static function getNumAvailablesNoSchedule($a_obj_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $all = ilBookingObject::getNrOfItemsForObjects(array($a_obj_id));
- $all = (int)$all[$a_obj_id];
-
- $set = $ilDB->query('SELECT COUNT(*) cnt'.
- ' FROM booking_reservation r'.
- ' JOIN booking_object o ON (o.booking_object_id = r.object_id)'.
- ' WHERE (status IS NULL OR status <> '.$ilDB->quote(self::STATUS_CANCELLED, 'integer').')'.
- ' AND r.object_id = '.$ilDB->quote($a_obj_id, 'integer'));
- $cnt = $ilDB->fetchAssoc($set);
- $cnt = (int)$cnt['cnt'];
-
- return (int)$all-$cnt; // #11864
- }
-
- /**
- * Get details about object reservation
- * @param int $a_object_id
- * @return array
- */
- static function getCurrentOrUpcomingReservation($a_object_id)
+ $res = array();
+ $query = 'SELECT DISTINCT bm.user_id user_id' .
+ ' FROM booking_member bm' .
+ ' WHERE bm.booking_pool_id = ' . $ilDB->quote($pool_id, 'integer') .
+ ' AND bm.user_id NOT IN (' .
+ 'SELECT user_id' .
+ ' FROM booking_reservation' .
+ ' WHERE object_id = ' . $ilDB->quote($a_object_id, 'integer') .
+ ' AND (status IS NULL OR status <> ' . ilBookingReservation::STATUS_CANCELLED . '))';
+
+ $set = $ilDB->query($query);
+
+ while ($row = $ilDB->fetchAssoc($set)) {
+ $res[] = $row['user_id'];
+ }
+
+ return $res;
+ }
+
+ public static function isObjectAvailableNoSchedule($a_obj_id)
{
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $now = $ilDB->quote(time(), 'integer');
-
- $ilDB->setLimit(1);
- $set = $ilDB->query('SELECT user_id, status, date_from, date_to'.
- ' FROM booking_reservation'.
- ' WHERE ((date_from <= '.$now.' AND date_to >= '.$now.')'.
- ' OR date_from > '.$now.')'.
- ' AND (status <> '.$ilDB->quote(self::STATUS_CANCELLED, 'integer').
- ' OR STATUS IS NULL) AND object_id = '.$ilDB->quote($a_object_id, 'integer').
- ' ORDER BY date_from');
- $row = $ilDB->fetchAssoc($set);
- return $row;
- }
-
- static function getObjectReservationForUser($a_object_id, $a_user_id, $a_multi = false)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $set = $ilDB->query('SELECT booking_reservation_id FROM booking_reservation'.
- ' WHERE user_id = '.$ilDB->quote($a_user_id, 'integer').
- ' AND object_id = '.$ilDB->quote($a_object_id, 'integer').
- ' AND (status <> '.$ilDB->quote(self::STATUS_CANCELLED, 'integer').
- ' OR STATUS IS NULL)');
- if(!$a_multi)
- {
- $row = $ilDB->fetchAssoc($set);
- return $row['booking_reservation_id'];
- }
- else
- {
- $res = array();
- while($row = $ilDB->fetchAssoc($set))
- {
- $res[] = $row['booking_reservation_id'];
- }
- return $res;
- }
- }
-
- /**
- * List all reservations
- * @param array $a_object_ids
- * @param int $a_limit
- * @param int $a_offset
- * @param array $a_offset
- * @return array
- */
- static function getList($a_object_ids, $a_limit = 10, $a_offset = 0, array $filter)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $sql = 'SELECT r.*,o.title'.
- ' FROM booking_reservation r'.
- ' JOIN booking_object o ON (o.booking_object_id = r.object_id)';
-
- $count_sql = 'SELECT COUNT(*) AS counter'.
- ' FROM booking_reservation r'.
- ' JOIN booking_object o ON (o.booking_object_id = r.object_id)';
-
- $where = array($ilDB->in('r.object_id', $a_object_ids, '', 'integer'));
- if($filter['status'])
- {
- if($filter['status'] > 0)
- {
- $where[] = 'status = '.$ilDB->quote($filter['status'], 'integer');
- }
- else
- {
- $where[] = '(status != '.$ilDB->quote(-$filter['status'], 'integer').
- ' OR status IS NULL)';
- }
- }
- if($filter['from'])
- {
- $where[] = 'date_from >= '.$ilDB->quote($filter['from'], 'integer');
- }
- if($filter['to'])
- {
- $where[] = 'date_to <= '.$ilDB->quote($filter['to'], 'integer');
- }
- if(sizeof($where))
- {
- $sql .= ' WHERE '.implode(' AND ', $where);
- $count_sql .= ' WHERE '.implode(' AND ', $where);
- }
-
- $set = $ilDB->query($count_sql);
- $row = $ilDB->fetchAssoc($set);
- $counter = $row['counter'];
-
- $sql .= ' ORDER BY date_from DESC, booking_reservation_id DESC';
-
- $ilDB->setLimit($a_limit, $a_offset);
- $set = $ilDB->query($sql);
- $res = array();
- while($row = $ilDB->fetchAssoc($set))
- {
- $res[] = $row;
- }
-
- return array('data'=>$res, 'counter'=>$counter);
- }
-
- /**
- * List all reservations by date
- * @param bool $a_has_schedule has schedule
- * @param array $a_object_ids object ids
- * @param array $filter filter
- * @param array $a_pool_ids pool ids
- * @return array
- */
- static function getListByDate($a_has_schedule, array $a_object_ids = null, array $filter = null,
- array $a_pool_ids = null)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $res = array();
-
- $sql = 'SELECT r.*, o.title, o.pool_id'.
- ' FROM booking_reservation r'.
- ' JOIN booking_object o ON (o.booking_object_id = r.object_id)';
-
- if ($a_pool_ids !== null)
- {
- $where = array($ilDB->in('pool_id', $a_pool_ids, '', 'integer'));
- }
-
- if ($a_object_ids !== null)
- {
- $where = array($ilDB->in('object_id', $a_object_ids, '', 'integer'));
- }
-
- if($filter['status'])
- {
- if($filter['status'] > 0)
- {
- $where[] = 'status = '.$ilDB->quote($filter['status'], 'integer');
- }
- else
- {
- $where[] = '(status != '.$ilDB->quote(-$filter['status'], 'integer').
- ' OR status IS NULL)';
- }
- }
- if($filter['title'])
- {
- $where[] = '('.$ilDB->like('title', 'text', '%'.$filter['title'].'%').
- ' OR '.$ilDB->like('description', 'text', '%'.$filter['title'].'%').')';
- }
- if($a_has_schedule)
- {
- if($filter['from'])
- {
- $where[] = 'date_from >= '.$ilDB->quote($filter['from'], 'integer');
- }
- if($filter['to'])
- {
- $where[] = 'date_to <= '.$ilDB->quote($filter['to'], 'integer');
- }
- if(!$filter['past'])
- {
- $where[] = 'date_to > '.$ilDB->quote(time(), 'integer');
- }
- }
- if($filter['user_id']) // #16584
- {
- $where[] = 'user_id = '.$ilDB->quote($filter['user_id'], 'integer');
- }
- /*
- if($a_group_id)
- {
- $where[] = 'group_id = '.$ilDB->quote(substr($a_group_id, 1), 'integer');
- }
- */
- if(sizeof($where))
- {
- $sql .= ' WHERE '.implode(' AND ', $where);
- }
-
- if($a_has_schedule)
- {
- $sql .= ' ORDER BY date_from DESC';
- }
- else
- {
- // #16155 - could be cancelled and re-booked
- $sql .= ' ORDER BY status';
- }
-
- $set = $ilDB->query($sql);
- while($row = $ilDB->fetchAssoc($set))
- {
- $obj_id = $row["object_id"];
- $user_id = $row["user_id"];
-
- if($a_has_schedule)
- {
- $slot = $row["date_from"]."_".$row["date_to"];
- $idx = $obj_id."_".$user_id."_".$slot;
- }
- else
- {
- $idx = $obj_id."_".$user_id;
- }
-
- if($a_has_schedule && $filter["slot"])
- {
- $slot_idx = date("w", $row["date_from"])."_".date("H:i", $row["date_from"]).
- "-".date("H:i", $row["date_to"]+1);
- if($filter["slot"] != $slot_idx)
- {
- continue;
- }
- }
-
- if(!isset($res[$idx]))
- {
- $uname = ilObjUser::_lookupName($user_id);
-
- $res[$idx] = array(
- "object_id" => $obj_id
- ,"title" => $row["title"]
- ,"pool_id" => $row["pool_id"]
- ,"user_id" => $user_id
- ,"counter" => 1
- ,"user_name" => $uname["lastname"].", ".$uname["firstname"] // #17862
- );
-
- if($a_has_schedule)
- {
- $res[$idx]["booking_reservation_id"] = $idx;
- $res[$idx]["date"] = date("Y-m-d", $row["date_from"]);
- $res[$idx]["slot"] = date("H:i", $row["date_from"])." - ".
- date("H:i", $row["date_to"]+1);
- $res[$idx]["week"] = date("W", $row["date_from"]);
- $res[$idx]["weekday"] = date("w", $row["date_from"]);
- $res[$idx]["can_be_cancelled"] = ($row["status"] != self::STATUS_CANCELLED &&
- $row["date_from"] > time());
- $res[$idx]["_sortdate"] = $row["date_from"];
- }
- else
- {
- $res[$idx]["booking_reservation_id"] = $row["booking_reservation_id"];
- $res[$idx]["status"] = $row["status"];
- $res[$idx]["can_be_cancelled"] = ($row["status"] != self::STATUS_CANCELLED);
- }
- }
- else
- {
- $res[$idx]["counter"]++;
- }
- }
-
- return $res;
- }
-
- /**
- * Get all users who have reservations for object(s)
- *
- * @param array $a_object_ids
- * @return array
- */
- public static function getUserFilter(array $a_object_ids)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $res = array();
-
- $sql = "SELECT ud.usr_id,ud.lastname,ud.firstname,ud.login".
- " FROM usr_data ud ".
- " LEFT JOIN booking_reservation r ON (r.user_id = ud.usr_id)".
- " WHERE ud.usr_id <> ".$ilDB->quote(ANONYMOUS_USER_ID, "integer").
- " AND ".$ilDB->in("r.object_id", $a_object_ids, "", "integer").
- " ORDER BY ud.lastname,ud.firstname";
- $set = $ilDB->query($sql);
- while($row = $ilDB->fetchAssoc($set))
- {
- $res[$row["usr_id"]] = $row["lastname"].", ".$row["firstname"].
- " (".$row["login"].")";
- }
-
- return $res;
- }
-
- /**
- * List all reservations
- * @param array $a_object_ids
- * @param int $a_limit
- * @param int $a_offset
- * @param array $filter
- * @param array $a_group_id
- * @return array
- */
- /*
- static function getGroupedList($a_object_ids, $a_limit = 10, $a_offset = 0, array $filter = null, $a_group_id = null)
- {
- global $ilDB;
-
- // CURRENTLY UNUSED!!!
- return;
-
- // find matching groups / reservations
-
- $sql = 'SELECT booking_reservation_id, group_id'.
- ' FROM booking_reservation';
-
- $where = array($ilDB->in('object_id', $a_object_ids, '', 'integer'));
- if($filter['status'])
- {
- if($filter['status'] > 0)
- {
- $where[] = 'status = '.$ilDB->quote($filter['status'], 'integer');
- }
- else
- {
- $where[] = '(status != '.$ilDB->quote(-$filter['status'], 'integer').
- ' OR status IS NULL)';
- }
- }
- if($filter['from'])
- {
- $where[] = 'date_from >= '.$ilDB->quote($filter['from'], 'integer');
- }
- if($filter['to'])
- {
- $where[] = 'date_to <= '.$ilDB->quote($filter['to'], 'integer');
- }
- if($filter['user_id'])
- {
- $where[] = 'user_id = '.$ilDB->quote($filter['user_id'], 'integer');
- }
- if($a_group_id)
- {
- $where[] = 'group_id = '.$ilDB->quote(substr($a_group_id, 1), 'integer');
- }
- if(sizeof($where))
- {
- $sql .= ' WHERE '.implode(' AND ', $where);
- }
-
- $grp_ids = $rsv_ids = array();
- $set = $ilDB->query($sql);
- while($row = $ilDB->fetchAssoc($set))
- {
- if($row["group_id"])
- {
- $grp_ids[] = $row["group_id"];
- }
- else
- {
- $rsv_ids[] = $row["booking_reservation_id"];
- }
- }
-
- $res = array();
-
- // get complete groups (and/or reservations)
-
- if($grp_ids || $rsv_ids)
- {
- $grp_ids = array_unique($grp_ids);
-
- // if result is on last page, reduce limit to entries on last page
- $max_page = sizeof($grp_ids)+sizeof($rsv_ids);
- $max_page = min($a_limit, $max_page-$a_offset);
-
- $sql = 'SELECT r.*,o.title'.
- ' FROM booking_reservation r'.
- ' JOIN booking_object o ON (o.booking_object_id = r.object_id)';
-
- $where = array();
- if($grp_ids)
- {
- $where[] = $ilDB->in('group_id', $grp_ids, '', 'integer');
- }
- if($rsv_ids)
- {
- $where[] = $ilDB->in('booking_reservation_id', $rsv_ids, '', 'integer');
- }
-
- $sql .= ' WHERE ('.implode(' OR ', $where).')'.
- ' ORDER BY date_from DESC, booking_reservation_id DESC';
-
- $set = $ilDB->query($sql);
- $grps = array();
- $counter = 0;
- while($row = $ilDB->fetchAssoc($set))
- {
- if($row["group_id"] && !$a_group_id)
- {
- if(!isset($grps[$row["group_id"]]))
- {
- $grps[$row["group_id"]] = 1;
- $counter++;
- }
- else
- {
- $grps[$row["group_id"]]++;
- }
- }
- else
- {
- $counter++;
- }
-
- if($a_group_id ||
- ($counter > $a_offset &&
- (sizeof($res) < $max_page ||
- // if group is current page we have to get all group entries, regardless of booking period
- ($row["group_id"] && isset($res["g".$row["group_id"]])))))
- {
- if($row["group_id"] && !$a_group_id)
- {
- $group_id = "g".$row["group_id"];
- $res[$group_id]["group_id"] = $group_id;
- $res[$group_id]["details"][] = $row;
- }
- else
- {
- unset($row["group_id"]);
- $res[] = $row;
- }
- }
- }
- }
-
- include_once('./Services/Calendar/classes/class.ilCalendarUtil.php');
-
- foreach($res as $idx => $item)
- {
- if(isset($item["details"]))
- {
- $res[$idx]["date_from"] = null;
- $res[$idx]["date_to"] = null;
-
- $weekdays = $week_counter = array();
- $recur = $last = 0;
-
- foreach($item["details"] as $detail)
- {
- // same for each item
- $res[$idx]["user_id"] = $detail["user_id"];
- $res[$idx]["object_id"] = $detail["object_id"];
- $res[$idx]["title"] = $detail["title"];
- $res[$idx]["booking_reservation_id"] = $detail["booking_reservation_id"];
-
- // recurrence/weekdays
- $sortkey = date("wHi", $detail["date_from"])."_".date("wHi", $detail["date_to"]);
- $weekdays[$sortkey] = ilCalendarUtil::_numericDayToString(date("w", $detail["date_from"]), false).
- ", ".date("H:i", $detail["date_from"]).
- " - ".date("H:i", $detail["date_to"]);
-
- if($detail["status"] != self::STATUS_CANCELLED)
- {
- $week_counter[$sortkey][date("WHi", $detail["date_from"])."_".date("WHi", $detail["date_to"])]++;
- }
- else if(!isset($week_counter[$sortkey][date("WHi", $detail["date_from"])."_".date("WHi", $detail["date_to"])]))
- {
- $week_counter[$sortkey][date("WHi", $detail["date_from"])."_".date("WHi", $detail["date_to"])] = 0;
- }
-
- if($last && $last-$detail["date_to"] > $recur)
- {
- $recur = $last-$detail["date_to"];
- }
-
- // min/max period
- if(!$res[$idx]["date_from"] || $detail["date_from"] < $res[$idx]["date_from"])
- {
- $res[$idx]["date_from"] = $detail["date_from"];
- }
- if(!$res[$idx]["date_to"] || $detail["date_to"] > $res[$idx]["date_to"])
- {
- $res[$idx]["date_to"] = $detail["date_to"];
- }
-
- $last = $detail["date_to"];
- }
-
- if(sizeof($item["details"]) > 1)
- {
- $weekdays = array_unique($weekdays);
- ksort($weekdays);
-
- foreach($weekdays as $week_id => $weekday)
- {
- $min = min($week_counter[$week_id]);
- $max = max($week_counter[$week_id]);
- if($min == $max)
- {
- $weekdays[$week_id] .= " (".$min.")";
- }
- else
- {
- $weekdays[$week_id] .= " (".$min."-".$max.")";
- }
- }
-
-
- $res[$idx]["weekdays"] = array_values($weekdays);
- if($recur)
- {
- if(date("YW", $res[$idx]["date_to"]) != date("YW", $res[$idx]["date_from"]))
- {
- $recur = ceil(($recur/(60*60*24))/7);
- }
- else
- {
- $recur = 0;
- }
- }
- $res[$idx]["recurrence"] = (int)$recur;
-
- $res[$idx]["booking_reservation_id"] = $idx;
- $res[$idx]["title"] .= " (".sizeof($item["details"]).")";
-
- }
- else
- {
- // undo grouping
- $res[$idx] = array_pop($item["details"]);
- unset($res[$idx]["group_id"]);
- }
- }
- }
-
- $res = ilUtil::sortArray($res, "date_from", "desc", true);
-
- return array('data'=>$res, 'counter'=>$counter);
- }
- */
-
- /**
- * Batch update reservation status
- * @param array $a_ids
- * @param int $a_status
- * @return bool
- */
- static function changeStatus(array $a_ids, $a_status)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- if(self::isValidStatus($a_status))
- {
- return $ilDB->manipulate('UPDATE booking_reservation'.
- ' SET status = '.$ilDB->quote($a_status, 'integer').
- ' WHERE '.$ilDB->in('booking_reservation_id', $a_ids, '', 'integer'));
-
- }
- }
-
- function getCalendarEntry()
- {
- $ilDB = $this->db;
-
- include_once 'Services/Calendar/classes/class.ilCalendarCategory.php';
-
- $set = $ilDB->query("SELECT ce.cal_id FROM cal_entries ce".
- " JOIN cal_cat_assignments cca ON ce.cal_id = cca.cal_id".
- " JOIN cal_categories cc ON cca.cat_id = cc.cat_id".
- " JOIN booking_reservation br ON ce.context_id = br.booking_reservation_id".
- " WHERE cc.obj_id = ".$ilDB->quote($this->getUserId(),'integer').
- " AND br.user_id = ".$ilDB->quote($this->getUserId(),'integer').
- " AND cc.type = ".$ilDB->quote(ilCalendarCategory::TYPE_BOOK,'integer').
- " AND ce.context_id = ".$ilDB->quote($this->getId(), 'integer'));
- $row = $ilDB->fetchAssoc($set);
- return $row["cal_id"];
- }
-
- /**
- * Get reservation ids from aggregated id for cancellation
- *
- * @param int $a_obj_id
- * @param int $a_user_id
- * @param int $a_from
- * @param int $a_to
- * @return array
- */
- public static function getCancelDetails($a_obj_id, $a_user_id, $a_from, $a_to)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $res = array();
-
- $sql = "SELECT booking_reservation_id".
- " FROM booking_reservation".
- " WHERE object_id = ".$ilDB->quote($a_obj_id, "integer").
- " AND user_id = ".$ilDB->quote($a_user_id, "integer").
- " AND date_from = ".$ilDB->quote($a_from, "integer").
- " AND date_to = ".$ilDB->quote($a_to, "integer").
- " AND (status IS NULL".
- " OR status <> ".$ilDB->quote(self::STATUS_CANCELLED, "integer").")";
- $set = $ilDB->query($sql);
- while($row = $ilDB->fetchAssoc($set))
- {
- $res[] = $row["booking_reservation_id"];
- }
-
- return $res;
- }
-}
+ $available = self::getNumAvailablesNoSchedule($a_obj_id);
+ return (bool) $available; // #11864
+ }
+ public static function numAvailableFromObjectNoSchedule($a_obj_id)
+ {
+ $available = self::getNumAvailablesNoSchedule($a_obj_id);
+ return (int) $available;
+ }
-?>
\ No newline at end of file
+ public static function getNumAvailablesNoSchedule($a_obj_id)
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ $all = ilBookingObject::getNrOfItemsForObjects(array($a_obj_id));
+ $all = (int) $all[$a_obj_id];
+
+ $set = $ilDB->query('SELECT COUNT(*) cnt' .
+ ' FROM booking_reservation r' .
+ ' JOIN booking_object o ON (o.booking_object_id = r.object_id)' .
+ ' WHERE (status IS NULL OR status <> ' . $ilDB->quote(self::STATUS_CANCELLED, 'integer') . ')' .
+ ' AND r.object_id = ' . $ilDB->quote($a_obj_id, 'integer'));
+ $cnt = $ilDB->fetchAssoc($set);
+ $cnt = (int) $cnt['cnt'];
+
+ return (int) $all-$cnt; // #11864
+ }
+
+ /**
+ * Get details about object reservation
+ * @param int $a_object_id
+ * @return array
+ */
+ public static function getCurrentOrUpcomingReservation($a_object_id)
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ $now = $ilDB->quote(time(), 'integer');
+
+ $ilDB->setLimit(1);
+ $set = $ilDB->query('SELECT user_id, status, date_from, date_to' .
+ ' FROM booking_reservation' .
+ ' WHERE ((date_from <= ' . $now . ' AND date_to >= ' . $now . ')' .
+ ' OR date_from > ' . $now . ')' .
+ ' AND (status <> ' . $ilDB->quote(self::STATUS_CANCELLED, 'integer') .
+ ' OR STATUS IS NULL) AND object_id = ' . $ilDB->quote($a_object_id, 'integer') .
+ ' ORDER BY date_from');
+ $row = $ilDB->fetchAssoc($set);
+ return $row;
+ }
+
+ public static function getObjectReservationForUser($a_object_id, $a_user_id, $a_multi = false)
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ $set = $ilDB->query('SELECT booking_reservation_id FROM booking_reservation' .
+ ' WHERE user_id = ' . $ilDB->quote($a_user_id, 'integer') .
+ ' AND object_id = ' . $ilDB->quote($a_object_id, 'integer') .
+ ' AND (status <> ' . $ilDB->quote(self::STATUS_CANCELLED, 'integer') .
+ ' OR STATUS IS NULL)');
+ if (!$a_multi) {
+ $row = $ilDB->fetchAssoc($set);
+ return $row['booking_reservation_id'];
+ } else {
+ $res = array();
+ while ($row = $ilDB->fetchAssoc($set)) {
+ $res[] = $row['booking_reservation_id'];
+ }
+ return $res;
+ }
+ }
+
+ /**
+ * List all reservations
+ * @param array $a_object_ids
+ * @param int $a_limit
+ * @param int $a_offset
+ * @param array $a_offset
+ * @return array
+ */
+ public static function getList($a_object_ids, $a_limit = 10, $a_offset = 0, array $filter)
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ $sql = 'SELECT r.*,o.title' .
+ ' FROM booking_reservation r' .
+ ' JOIN booking_object o ON (o.booking_object_id = r.object_id)';
+
+ $count_sql = 'SELECT COUNT(*) AS counter' .
+ ' FROM booking_reservation r' .
+ ' JOIN booking_object o ON (o.booking_object_id = r.object_id)';
+
+ $where = array($ilDB->in('r.object_id', $a_object_ids, '', 'integer'));
+ if ($filter['status']) {
+ if ($filter['status'] > 0) {
+ $where[] = 'status = ' . $ilDB->quote($filter['status'], 'integer');
+ } else {
+ $where[] = '(status != ' . $ilDB->quote(-$filter['status'], 'integer') .
+ ' OR status IS NULL)';
+ }
+ }
+ if ($filter['from']) {
+ $where[] = 'date_from >= ' . $ilDB->quote($filter['from'], 'integer');
+ }
+ if ($filter['to']) {
+ $where[] = 'date_to <= ' . $ilDB->quote($filter['to'], 'integer');
+ }
+ if (sizeof($where)) {
+ $sql .= ' WHERE ' . implode(' AND ', $where);
+ $count_sql .= ' WHERE ' . implode(' AND ', $where);
+ }
+
+ $set = $ilDB->query($count_sql);
+ $row = $ilDB->fetchAssoc($set);
+ $counter = $row['counter'];
+
+ $sql .= ' ORDER BY date_from DESC, booking_reservation_id DESC';
+
+ $ilDB->setLimit($a_limit, $a_offset);
+ $set = $ilDB->query($sql);
+ $res = array();
+ while ($row = $ilDB->fetchAssoc($set)) {
+ $res[] = $row;
+ }
+
+ return array('data'=>$res, 'counter'=>$counter);
+ }
+
+ /**
+ * List all reservations by date
+ * @param bool $a_has_schedule has schedule
+ * @param array $a_object_ids object ids
+ * @param array $filter filter
+ * @param array $a_pool_ids pool ids
+ * @return array
+ */
+ public static function getListByDate(
+ $a_has_schedule,
+ array $a_object_ids = null,
+ array $filter = null,
+ array $a_pool_ids = null
+ ) {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ $res = array();
+
+ $sql = 'SELECT r.*, o.title, o.pool_id' .
+ ' FROM booking_reservation r' .
+ ' JOIN booking_object o ON (o.booking_object_id = r.object_id)';
+
+ if ($a_pool_ids !== null) {
+ $where = array($ilDB->in('pool_id', $a_pool_ids, '', 'integer'));
+ }
+
+ if ($a_object_ids !== null) {
+ $where = array($ilDB->in('object_id', $a_object_ids, '', 'integer'));
+ }
+
+ if ($filter['status']) {
+ if ($filter['status'] > 0) {
+ $where[] = 'status = ' . $ilDB->quote($filter['status'], 'integer');
+ } else {
+ $where[] = '(status != ' . $ilDB->quote(-$filter['status'], 'integer') .
+ ' OR status IS NULL)';
+ }
+ }
+ if ($filter['title']) {
+ $where[] = '(' . $ilDB->like('title', 'text', '%' . $filter['title'] . '%') .
+ ' OR ' . $ilDB->like('description', 'text', '%' . $filter['title'] . '%') . ')';
+ }
+ if ($a_has_schedule) {
+ if ($filter['from']) {
+ $where[] = 'date_from >= ' . $ilDB->quote($filter['from'], 'integer');
+ }
+ if ($filter['to']) {
+ $where[] = 'date_to <= ' . $ilDB->quote($filter['to'], 'integer');
+ }
+ if (!$filter['past']) {
+ $where[] = 'date_to > ' . $ilDB->quote(time(), 'integer');
+ }
+ }
+ if ($filter['user_id']) { // #16584
+ $where[] = 'user_id = ' . $ilDB->quote($filter['user_id'], 'integer');
+ }
+ /*
+ if($a_group_id)
+ {
+ $where[] = 'group_id = '.$ilDB->quote(substr($a_group_id, 1), 'integer');
+ }
+ */
+ if (sizeof($where)) {
+ $sql .= ' WHERE ' . implode(' AND ', $where);
+ }
+
+ if ($a_has_schedule) {
+ $sql .= ' ORDER BY date_from DESC';
+ } else {
+ // #16155 - could be cancelled and re-booked
+ $sql .= ' ORDER BY status';
+ }
+
+ $set = $ilDB->query($sql);
+ while ($row = $ilDB->fetchAssoc($set)) {
+ $obj_id = $row["object_id"];
+ $user_id = $row["user_id"];
+
+ if ($a_has_schedule) {
+ $slot = $row["date_from"] . "_" . $row["date_to"];
+ $idx = $obj_id . "_" . $user_id . "_" . $slot;
+ } else {
+ $idx = $obj_id . "_" . $user_id;
+ }
+
+ if ($a_has_schedule && $filter["slot"]) {
+ $slot_idx = date("w", $row["date_from"]) . "_" . date("H:i", $row["date_from"]) .
+ "-" . date("H:i", $row["date_to"]+1);
+ if ($filter["slot"] != $slot_idx) {
+ continue;
+ }
+ }
+
+ if (!isset($res[$idx])) {
+ $uname = ilObjUser::_lookupName($user_id);
+
+ $res[$idx] = array(
+ "object_id" => $obj_id
+ ,"title" => $row["title"]
+ ,"pool_id" => $row["pool_id"]
+ ,"user_id" => $user_id
+ ,"counter" => 1
+ ,"user_name" => $uname["lastname"] . ", " . $uname["firstname"] // #17862
+ );
+
+ if ($a_has_schedule) {
+ $res[$idx]["booking_reservation_id"] = $idx;
+ $res[$idx]["date"] = date("Y-m-d", $row["date_from"]);
+ $res[$idx]["slot"] = date("H:i", $row["date_from"]) . " - " .
+ date("H:i", $row["date_to"]+1);
+ $res[$idx]["week"] = date("W", $row["date_from"]);
+ $res[$idx]["weekday"] = date("w", $row["date_from"]);
+ $res[$idx]["can_be_cancelled"] = ($row["status"] != self::STATUS_CANCELLED &&
+ $row["date_from"] > time());
+ $res[$idx]["_sortdate"] = $row["date_from"];
+ } else {
+ $res[$idx]["booking_reservation_id"] = $row["booking_reservation_id"];
+ $res[$idx]["status"] = $row["status"];
+ $res[$idx]["can_be_cancelled"] = ($row["status"] != self::STATUS_CANCELLED);
+ }
+ } else {
+ $res[$idx]["counter"]++;
+ }
+ }
+
+ return $res;
+ }
+
+ /**
+ * Get all users who have reservations for object(s)
+ *
+ * @param array $a_object_ids
+ * @return array
+ */
+ public static function getUserFilter(array $a_object_ids)
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ $res = array();
+
+ $sql = "SELECT ud.usr_id,ud.lastname,ud.firstname,ud.login" .
+ " FROM usr_data ud " .
+ " LEFT JOIN booking_reservation r ON (r.user_id = ud.usr_id)" .
+ " WHERE ud.usr_id <> " . $ilDB->quote(ANONYMOUS_USER_ID, "integer") .
+ " AND " . $ilDB->in("r.object_id", $a_object_ids, "", "integer") .
+ " ORDER BY ud.lastname,ud.firstname";
+ $set = $ilDB->query($sql);
+ while ($row = $ilDB->fetchAssoc($set)) {
+ $res[$row["usr_id"]] = $row["lastname"] . ", " . $row["firstname"] .
+ " (" . $row["login"] . ")";
+ }
+
+ return $res;
+ }
+
+ /**
+ * List all reservations
+ * @param array $a_object_ids
+ * @param int $a_limit
+ * @param int $a_offset
+ * @param array $filter
+ * @param array $a_group_id
+ * @return array
+ */
+ /*
+ static function getGroupedList($a_object_ids, $a_limit = 10, $a_offset = 0, array $filter = null, $a_group_id = null)
+ {
+ global $ilDB;
+
+ // CURRENTLY UNUSED!!!
+ return;
+
+ // find matching groups / reservations
+
+ $sql = 'SELECT booking_reservation_id, group_id'.
+ ' FROM booking_reservation';
+
+ $where = array($ilDB->in('object_id', $a_object_ids, '', 'integer'));
+ if($filter['status'])
+ {
+ if($filter['status'] > 0)
+ {
+ $where[] = 'status = '.$ilDB->quote($filter['status'], 'integer');
+ }
+ else
+ {
+ $where[] = '(status != '.$ilDB->quote(-$filter['status'], 'integer').
+ ' OR status IS NULL)';
+ }
+ }
+ if($filter['from'])
+ {
+ $where[] = 'date_from >= '.$ilDB->quote($filter['from'], 'integer');
+ }
+ if($filter['to'])
+ {
+ $where[] = 'date_to <= '.$ilDB->quote($filter['to'], 'integer');
+ }
+ if($filter['user_id'])
+ {
+ $where[] = 'user_id = '.$ilDB->quote($filter['user_id'], 'integer');
+ }
+ if($a_group_id)
+ {
+ $where[] = 'group_id = '.$ilDB->quote(substr($a_group_id, 1), 'integer');
+ }
+ if(sizeof($where))
+ {
+ $sql .= ' WHERE '.implode(' AND ', $where);
+ }
+
+ $grp_ids = $rsv_ids = array();
+ $set = $ilDB->query($sql);
+ while($row = $ilDB->fetchAssoc($set))
+ {
+ if($row["group_id"])
+ {
+ $grp_ids[] = $row["group_id"];
+ }
+ else
+ {
+ $rsv_ids[] = $row["booking_reservation_id"];
+ }
+ }
+
+ $res = array();
+
+ // get complete groups (and/or reservations)
+
+ if($grp_ids || $rsv_ids)
+ {
+ $grp_ids = array_unique($grp_ids);
+
+ // if result is on last page, reduce limit to entries on last page
+ $max_page = sizeof($grp_ids)+sizeof($rsv_ids);
+ $max_page = min($a_limit, $max_page-$a_offset);
+
+ $sql = 'SELECT r.*,o.title'.
+ ' FROM booking_reservation r'.
+ ' JOIN booking_object o ON (o.booking_object_id = r.object_id)';
+
+ $where = array();
+ if($grp_ids)
+ {
+ $where[] = $ilDB->in('group_id', $grp_ids, '', 'integer');
+ }
+ if($rsv_ids)
+ {
+ $where[] = $ilDB->in('booking_reservation_id', $rsv_ids, '', 'integer');
+ }
+
+ $sql .= ' WHERE ('.implode(' OR ', $where).')'.
+ ' ORDER BY date_from DESC, booking_reservation_id DESC';
+
+ $set = $ilDB->query($sql);
+ $grps = array();
+ $counter = 0;
+ while($row = $ilDB->fetchAssoc($set))
+ {
+ if($row["group_id"] && !$a_group_id)
+ {
+ if(!isset($grps[$row["group_id"]]))
+ {
+ $grps[$row["group_id"]] = 1;
+ $counter++;
+ }
+ else
+ {
+ $grps[$row["group_id"]]++;
+ }
+ }
+ else
+ {
+ $counter++;
+ }
+
+ if($a_group_id ||
+ ($counter > $a_offset &&
+ (sizeof($res) < $max_page ||
+ // if group is current page we have to get all group entries, regardless of booking period
+ ($row["group_id"] && isset($res["g".$row["group_id"]])))))
+ {
+ if($row["group_id"] && !$a_group_id)
+ {
+ $group_id = "g".$row["group_id"];
+ $res[$group_id]["group_id"] = $group_id;
+ $res[$group_id]["details"][] = $row;
+ }
+ else
+ {
+ unset($row["group_id"]);
+ $res[] = $row;
+ }
+ }
+ }
+ }
+
+ include_once('./Services/Calendar/classes/class.ilCalendarUtil.php');
+
+ foreach($res as $idx => $item)
+ {
+ if(isset($item["details"]))
+ {
+ $res[$idx]["date_from"] = null;
+ $res[$idx]["date_to"] = null;
+
+ $weekdays = $week_counter = array();
+ $recur = $last = 0;
+
+ foreach($item["details"] as $detail)
+ {
+ // same for each item
+ $res[$idx]["user_id"] = $detail["user_id"];
+ $res[$idx]["object_id"] = $detail["object_id"];
+ $res[$idx]["title"] = $detail["title"];
+ $res[$idx]["booking_reservation_id"] = $detail["booking_reservation_id"];
+
+ // recurrence/weekdays
+ $sortkey = date("wHi", $detail["date_from"])."_".date("wHi", $detail["date_to"]);
+ $weekdays[$sortkey] = ilCalendarUtil::_numericDayToString(date("w", $detail["date_from"]), false).
+ ", ".date("H:i", $detail["date_from"]).
+ " - ".date("H:i", $detail["date_to"]);
+
+ if($detail["status"] != self::STATUS_CANCELLED)
+ {
+ $week_counter[$sortkey][date("WHi", $detail["date_from"])."_".date("WHi", $detail["date_to"])]++;
+ }
+ else if(!isset($week_counter[$sortkey][date("WHi", $detail["date_from"])."_".date("WHi", $detail["date_to"])]))
+ {
+ $week_counter[$sortkey][date("WHi", $detail["date_from"])."_".date("WHi", $detail["date_to"])] = 0;
+ }
+
+ if($last && $last-$detail["date_to"] > $recur)
+ {
+ $recur = $last-$detail["date_to"];
+ }
+
+ // min/max period
+ if(!$res[$idx]["date_from"] || $detail["date_from"] < $res[$idx]["date_from"])
+ {
+ $res[$idx]["date_from"] = $detail["date_from"];
+ }
+ if(!$res[$idx]["date_to"] || $detail["date_to"] > $res[$idx]["date_to"])
+ {
+ $res[$idx]["date_to"] = $detail["date_to"];
+ }
+
+ $last = $detail["date_to"];
+ }
+
+ if(sizeof($item["details"]) > 1)
+ {
+ $weekdays = array_unique($weekdays);
+ ksort($weekdays);
+
+ foreach($weekdays as $week_id => $weekday)
+ {
+ $min = min($week_counter[$week_id]);
+ $max = max($week_counter[$week_id]);
+ if($min == $max)
+ {
+ $weekdays[$week_id] .= " (".$min.")";
+ }
+ else
+ {
+ $weekdays[$week_id] .= " (".$min."-".$max.")";
+ }
+ }
+
+
+ $res[$idx]["weekdays"] = array_values($weekdays);
+ if($recur)
+ {
+ if(date("YW", $res[$idx]["date_to"]) != date("YW", $res[$idx]["date_from"]))
+ {
+ $recur = ceil(($recur/(60*60*24))/7);
+ }
+ else
+ {
+ $recur = 0;
+ }
+ }
+ $res[$idx]["recurrence"] = (int)$recur;
+
+ $res[$idx]["booking_reservation_id"] = $idx;
+ $res[$idx]["title"] .= " (".sizeof($item["details"]).")";
+
+ }
+ else
+ {
+ // undo grouping
+ $res[$idx] = array_pop($item["details"]);
+ unset($res[$idx]["group_id"]);
+ }
+ }
+ }
+
+ $res = ilUtil::sortArray($res, "date_from", "desc", true);
+
+ return array('data'=>$res, 'counter'=>$counter);
+ }
+ */
+
+ /**
+ * Batch update reservation status
+ * @param array $a_ids
+ * @param int $a_status
+ * @return bool
+ */
+ public static function changeStatus(array $a_ids, $a_status)
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ if (self::isValidStatus($a_status)) {
+ return $ilDB->manipulate('UPDATE booking_reservation' .
+ ' SET status = ' . $ilDB->quote($a_status, 'integer') .
+ ' WHERE ' . $ilDB->in('booking_reservation_id', $a_ids, '', 'integer'));
+ }
+ }
+
+ public function getCalendarEntry()
+ {
+ $ilDB = $this->db;
+
+ include_once 'Services/Calendar/classes/class.ilCalendarCategory.php';
+
+ $set = $ilDB->query("SELECT ce.cal_id FROM cal_entries ce" .
+ " JOIN cal_cat_assignments cca ON ce.cal_id = cca.cal_id" .
+ " JOIN cal_categories cc ON cca.cat_id = cc.cat_id" .
+ " JOIN booking_reservation br ON ce.context_id = br.booking_reservation_id" .
+ " WHERE cc.obj_id = " . $ilDB->quote($this->getUserId(), 'integer') .
+ " AND br.user_id = " . $ilDB->quote($this->getUserId(), 'integer') .
+ " AND cc.type = " . $ilDB->quote(ilCalendarCategory::TYPE_BOOK, 'integer') .
+ " AND ce.context_id = " . $ilDB->quote($this->getId(), 'integer'));
+ $row = $ilDB->fetchAssoc($set);
+ return $row["cal_id"];
+ }
+
+ /**
+ * Get reservation ids from aggregated id for cancellation
+ *
+ * @param int $a_obj_id
+ * @param int $a_user_id
+ * @param int $a_from
+ * @param int $a_to
+ * @return array
+ */
+ public static function getCancelDetails($a_obj_id, $a_user_id, $a_from, $a_to)
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ $res = array();
+
+ $sql = "SELECT booking_reservation_id" .
+ " FROM booking_reservation" .
+ " WHERE object_id = " . $ilDB->quote($a_obj_id, "integer") .
+ " AND user_id = " . $ilDB->quote($a_user_id, "integer") .
+ " AND date_from = " . $ilDB->quote($a_from, "integer") .
+ " AND date_to = " . $ilDB->quote($a_to, "integer") .
+ " AND (status IS NULL" .
+ " OR status <> " . $ilDB->quote(self::STATUS_CANCELLED, "integer") . ")";
+ $set = $ilDB->query($sql);
+ while ($row = $ilDB->fetchAssoc($set)) {
+ $res[] = $row["booking_reservation_id"];
+ }
+
+ return $res;
+ }
+}
diff --git a/Modules/BookingManager/classes/class.ilBookingReservationsTableGUI.php b/Modules/BookingManager/classes/class.ilBookingReservationsTableGUI.php
index 9bf3c309666cf96d9f2196c96ef5452649606a4b..167c6f1414204cc74c32cd247a898a11d381531c 100644
--- a/Modules/BookingManager/classes/class.ilBookingReservationsTableGUI.php
+++ b/Modules/BookingManager/classes/class.ilBookingReservationsTableGUI.php
@@ -6,899 +6,797 @@ include_once 'Modules/BookingManager/classes/class.ilBookingReservation.php';
require_once "Services/Calendar/classes/class.ilCalendarUtil.php";
/**
- * List booking objects
+ * List booking objects
*
- * @author Jörg Lützenkirchen
".print_r($a_mapping, true)."
"; exit;
- // get all categories of the import
- include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php");
- $maps = $a_mapping->getMappingsOfEntity("Modules/Category", "cat");
- foreach ($maps as $old => $new)
- {
- if ($old != "new_id" && (int) $old > 0)
- {
- // get all new taxonomys of this object
- $new_tax_ids = $a_mapping->getMapping("Services/Taxonomy", "tax_usage_of_obj", $old);
- $tax_ids = explode(":", $new_tax_ids);
- foreach ($tax_ids as $tid)
- {
- ilObjTaxonomy::saveUsage($tid, $new);
- }
- }
- }
- }
-
+ // this is since 4.3 does not export these ids but 4.4 tax node assignment needs it
+ $a_mapping->addMapping(
+ "Services/Taxonomy",
+ "tax_item_obj_id",
+ $type . ":obj:" . $old,
+ $new
+ );
+ }
+ }
+
+ /**
+ * Final processing
+ *
+ * @param
+ * @return
+ */
+ public function finalProcessing($a_mapping)
+ {
+ //echo "".print_r($a_mapping, true)."
"; exit;
+ // get all categories of the import
+ include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php");
+ $maps = $a_mapping->getMappingsOfEntity("Modules/Category", "cat");
+ foreach ($maps as $old => $new) {
+ if ($old != "new_id" && (int) $old > 0) {
+ // get all new taxonomys of this object
+ $new_tax_ids = $a_mapping->getMapping("Services/Taxonomy", "tax_usage_of_obj", $old);
+ $tax_ids = explode(":", $new_tax_ids);
+ foreach ($tax_ids as $tid) {
+ ilObjTaxonomy::saveUsage($tid, $new);
+ }
+ }
+ }
+ }
}
-?>
diff --git a/Modules/Category/classes/class.ilCategoryXmlParser.php b/Modules/Category/classes/class.ilCategoryXmlParser.php
index 4aa59a88d03281984735fbb9d50c20cf61e10253..c8c4d2f5331cf459848f3e298d1623d48465444c 100644
--- a/Modules/Category/classes/class.ilCategoryXmlParser.php
+++ b/Modules/Category/classes/class.ilCategoryXmlParser.php
@@ -1,24 +1,24 @@
error = $DIC["ilErr"];
- parent::__construct(null);
-
- $this->mode = ilCategoryXmlParser::MODE_CREATE;
- $this->parent_id = $a_parent_id;
- $this->setXMLContent($a_xml);
-
- $this->cat_log = ilLoggerFactory::getLogger("cat");
- }
-
- /**
- * Get parent id
- * @return type
- */
- public function getParentId()
- {
- return $this->parent_id;
- }
-
- /**
- * Get current translation
- */
- protected function getCurrentTranslation()
- {
- return $this->current_translation;
- }
-
-
-
- /**
- * set event handler
- * should be overwritten by inherited class
- * @access private
- */
- public function setHandlers($a_xml_parser)
- {
- xml_set_object($a_xml_parser,$this);
- xml_set_element_handler($a_xml_parser,'handlerBeginTag','handlerEndTag');
- xml_set_character_data_handler($a_xml_parser,'handlerCharacterData');
- }
-
- /**
- * start the parser
- */
- public function startParsing()
- {
- parent::startParsing();
-
- if ($this->mode == ilCategoryXmlParser::MODE_CREATE)
- {
- return is_object($this->cat) ? $this->cat->getRefId() : false;
- }
- else
- {
- return is_object($this->cat) ? $this->cat->update() : false;
- }
- }
-
-
- /**
- * handler for begin of element
- */
- public function handlerBeginTag($a_xml_parser, $a_name, $a_attribs)
- {
- $ilErr = $this->error;
-
- switch($a_name)
- {
- case "Category":
- break;
-
- case 'Translations':
- $this->getCategory()->removeTranslations();
- break;
-
- case 'Translation':
- $this->current_translation = array();
- $this->current_translation['default'] = $a_attribs['default'] ? 1 : 0;
- $this->current_translation['lang'] = $a_attribs['language'];
- break;
-
- case 'Sorting':
- case 'Sort':
- include_once './Services/Container/classes/class.ilContainerSortingSettings.php';
- ilContainerSortingSettings::_importContainerSortingSettings($a_attribs, $this->getCategory()->getId());
- break;
-
- case 'ContainerSetting':
- $this->current_container_setting = $a_attribs['id'];
- break;
- }
- }
-
-
- /**
- * Handler end tag
- * @param type $a_xml_parser
- * @param type $a_name
- */
- public function handlerEndTag($a_xml_parser, $a_name)
- {
- switch($a_name)
- {
- case "Category":
- $this->save();
- break;
-
- case 'Title':
- $this->current_translation['title'] = trim($this->cdata);
-
- if($this->current_translation['default'])
- {
- $this->getCategory()->setTitle(trim($this->cdata));
- }
-
- break;
-
- case 'Description':
- $this->current_translation['description'] = trim($this->cdata);
-
- if($this->current_translation['default'])
- {
- $this->getCategory()->setDescription(trim($this->cdata));
- }
-
- break;
-
- case 'Translation':
- // Add translation
- $this->getCategory()->addTranslation(
- (string) $this->current_translation['title'],
- (string) $this->current_translation['description'],
- (string) $this->current_translation['lang'],
- (int) $this->current_translation['default']
- );
- break;
-
- case 'ContainerSetting':
- if($this->current_container_setting)
- {
- $this->cat_log->debug("Write container Setting, ID: ".$this->getCategory()->getId().", setting: ".
- $this->current_container_setting.", data: ".$this->cdata);
- ilContainer::_writeContainerSetting(
- $this->getCategory()->getId(),
- $this->current_container_setting,
- $this->cdata);
- }
- break;
-
- case 'ContainerSettings':
- $this->cat->readContainerSettings(); // read container settings to member vars (call getter/setter), see #0019870
- break;
- }
- $this->cdata = '';
- }
-
-
- /**
- * handler for character data
- */
- function handlerCharacterData($a_xml_parser, $a_data)
- {
- #$a_data = str_replace("<","<",$a_data);
- #$a_data = str_replace(">",">",$a_data);
-
- if(!empty($a_data))
- {
- $this->cdata .= $a_data;
- }
- }
-
- /**
- * Save category object
- * @return type
- */
- protected function save()
- {
-
- /**
- * mode can be create or update
- */
- if ($this->mode == ilCategoryXmlParser::MODE_CREATE)
- {
- $this->create();
- $this->getCategory()->create();
- $this->getCategory()->createReference();
- $this->getCategory()->putInTree($this->getParentId());
- $this->getCategory()->setPermissions($this->getParentId());
- }
- $this->getCategory()->update();
- return true;
- }
-
-
-
-
- /**
- * Set import mode
- * @param type $mode
- */
- public function setMode($mode)
- {
- $this->mode = $mode;
- }
-
- /**
- * Set category object
- * @param type $cat
- */
- public function setCategory($cat)
- {
- $this->cat = $cat;
- }
-
- public function getCategory()
- {
- return $this->cat;
- }
+ /**
+ * @var ilErrorHandling
+ */
+ protected $error;
+
+ const MODE_CREATE = 1;
+ const MODE_UPDATE = 2;
+
+ private $cat = null;
+ private $parent_id = 0;
+
+ private $current_translation = array();
+ private $current_container_setting;
+
+
+ /**
+ * @var ilLogger
+ */
+ protected $cat_log;
+
+ /**
+ * Constructor
+ *
+ * @param string $a_xml_file xml file
+ *
+ * @access public
+ */
+
+ public function __construct($a_xml, $a_parent_id)
+ {
+ global $DIC;
+
+ $this->error = $DIC["ilErr"];
+ parent::__construct(null);
+
+ $this->mode = ilCategoryXmlParser::MODE_CREATE;
+ $this->parent_id = $a_parent_id;
+ $this->setXMLContent($a_xml);
+
+ $this->cat_log = ilLoggerFactory::getLogger("cat");
+ }
+
+ /**
+ * Get parent id
+ * @return type
+ */
+ public function getParentId()
+ {
+ return $this->parent_id;
+ }
+
+ /**
+ * Get current translation
+ */
+ protected function getCurrentTranslation()
+ {
+ return $this->current_translation;
+ }
+
+
+
+ /**
+ * set event handler
+ * should be overwritten by inherited class
+ * @access private
+ */
+ public function setHandlers($a_xml_parser)
+ {
+ xml_set_object($a_xml_parser, $this);
+ xml_set_element_handler($a_xml_parser, 'handlerBeginTag', 'handlerEndTag');
+ xml_set_character_data_handler($a_xml_parser, 'handlerCharacterData');
+ }
+
+ /**
+ * start the parser
+ */
+ public function startParsing()
+ {
+ parent::startParsing();
+
+ if ($this->mode == ilCategoryXmlParser::MODE_CREATE) {
+ return is_object($this->cat) ? $this->cat->getRefId() : false;
+ } else {
+ return is_object($this->cat) ? $this->cat->update() : false;
+ }
+ }
+
+
+ /**
+ * handler for begin of element
+ */
+ public function handlerBeginTag($a_xml_parser, $a_name, $a_attribs)
+ {
+ $ilErr = $this->error;
+
+ switch ($a_name) {
+ case "Category":
+ break;
+
+ case 'Translations':
+ $this->getCategory()->removeTranslations();
+ break;
+
+ case 'Translation':
+ $this->current_translation = array();
+ $this->current_translation['default'] = $a_attribs['default'] ? 1 : 0;
+ $this->current_translation['lang'] = $a_attribs['language'];
+ break;
+
+ case 'Sorting':
+ case 'Sort':
+ include_once './Services/Container/classes/class.ilContainerSortingSettings.php';
+ ilContainerSortingSettings::_importContainerSortingSettings($a_attribs, $this->getCategory()->getId());
+ break;
+
+ case 'ContainerSetting':
+ $this->current_container_setting = $a_attribs['id'];
+ break;
+ }
+ }
+
+
+ /**
+ * Handler end tag
+ * @param type $a_xml_parser
+ * @param type $a_name
+ */
+ public function handlerEndTag($a_xml_parser, $a_name)
+ {
+ switch ($a_name) {
+ case "Category":
+ $this->save();
+ break;
+
+ case 'Title':
+ $this->current_translation['title'] = trim($this->cdata);
+
+ if ($this->current_translation['default']) {
+ $this->getCategory()->setTitle(trim($this->cdata));
+ }
+
+ break;
+
+ case 'Description':
+ $this->current_translation['description'] = trim($this->cdata);
+
+ if ($this->current_translation['default']) {
+ $this->getCategory()->setDescription(trim($this->cdata));
+ }
+
+ break;
+
+ case 'Translation':
+ // Add translation
+ $this->getCategory()->addTranslation(
+ (string) $this->current_translation['title'],
+ (string) $this->current_translation['description'],
+ (string) $this->current_translation['lang'],
+ (int) $this->current_translation['default']
+ );
+ break;
+
+ case 'ContainerSetting':
+ if ($this->current_container_setting) {
+ $this->cat_log->debug("Write container Setting, ID: " . $this->getCategory()->getId() . ", setting: " .
+ $this->current_container_setting . ", data: " . $this->cdata);
+ ilContainer::_writeContainerSetting(
+ $this->getCategory()->getId(),
+ $this->current_container_setting,
+ $this->cdata
+ );
+ }
+ break;
+
+ case 'ContainerSettings':
+ $this->cat->readContainerSettings(); // read container settings to member vars (call getter/setter), see #0019870
+ break;
+ }
+ $this->cdata = '';
+ }
+
+
+ /**
+ * handler for character data
+ */
+ public function handlerCharacterData($a_xml_parser, $a_data)
+ {
+ #$a_data = str_replace("<","<",$a_data);
+ #$a_data = str_replace(">",">",$a_data);
+
+ if (!empty($a_data)) {
+ $this->cdata .= $a_data;
+ }
+ }
+
+ /**
+ * Save category object
+ * @return type
+ */
+ protected function save()
+ {
+
+ /**
+ * mode can be create or update
+ */
+ if ($this->mode == ilCategoryXmlParser::MODE_CREATE) {
+ $this->create();
+ $this->getCategory()->create();
+ $this->getCategory()->createReference();
+ $this->getCategory()->putInTree($this->getParentId());
+ $this->getCategory()->setPermissions($this->getParentId());
+ }
+ $this->getCategory()->update();
+ return true;
+ }
+
+
+
+
+ /**
+ * Set import mode
+ * @param type $mode
+ */
+ public function setMode($mode)
+ {
+ $this->mode = $mode;
+ }
+
+ /**
+ * Set category object
+ * @param type $cat
+ */
+ public function setCategory($cat)
+ {
+ $this->cat = $cat;
+ }
+
+ public function getCategory()
+ {
+ return $this->cat;
+ }
}
-?>
diff --git a/Modules/Category/classes/class.ilCategoryXmlWriter.php b/Modules/Category/classes/class.ilCategoryXmlWriter.php
index 9926438e7ea8be9ce2276e78779238c136ad662d..7b018365e827ecb3eef4683f02c6d1f1ec9cb079 100644
--- a/Modules/Category/classes/class.ilCategoryXmlWriter.php
+++ b/Modules/Category/classes/class.ilCategoryXmlWriter.php
@@ -11,147 +11,145 @@ include_once "./Services/Xml/classes/class.ilXmlWriter.php";
*/
class ilCategoryXmlWriter extends ilXmlWriter
{
- /**
- * @var ilSetting
- */
- protected $settings;
-
- const MODE_SOAP = 1;
- const MODE_EXPORT = 2;
-
- private $mode = self::MODE_SOAP;
- private $xml;
- private $category;
-
- /**
- * constructor
- * @param string xml version
- * @param string output encoding
- * @param string input encoding
- * @access public
- */
- public function __construct(ilObjCategory $cat = null)
- {
- global $DIC;
-
- $this->settings = $DIC->settings();
- parent::__construct();
-
- $this->category = $cat;
- }
-
- /**
- * Set export mode
- * @param int $a_mode
- */
- public function setMode($a_mode)
- {
- $this->mode = $a_mode;
- }
-
- /**
- * get export mode
- * @return int
- */
- public function getMode()
- {
- return $this->mode;
- }
-
- /**
- * Get category object
- * @return ilObjCategory
- */
- public function getCategory()
- {
- return $this->category;
- }
-
-
- /**
- * Start wrting xml
- */
- public function export($a_with_header = true)
- {
- if($this->getMode() == self::MODE_EXPORT)
- {
- if($a_with_header)
- {
- $this->buildHeader();
- }
- $this->buildCategory();
- $this->buildTranslations();
- include_once './Services/Container/classes/class.ilContainerSortingSettings.php';
- ilContainerSortingSettings::_exportContainerSortingSettings($this,$this->getCategory()->getId());
- include_once './Services/Container/classes/class.ilContainer.php';
- ilContainer::_exportContainerSettings($this, $this->category->getId());
- $this->buildFooter();
- }
- }
-
- /**
- * get XML
- * @return string
- */
- public function getXml()
- {
- return $this->xmlDumpMem(false);
- }
-
- /**
- * Build xml header
- * @global
(".ilDatePresentation::formatDate(new ilDateTime($d["deadline2"],IL_CAL_UNIX)).")";
- }
- $this->tpl->setVariable("TXT_DEADLINE", $dl);
- }
- if ($d["start_time"] > 0)
- {
- $this->tpl->setVariable("TXT_START_TIME",
- ilDatePresentation::formatDate(new ilDateTime($d["start_time"],IL_CAL_UNIX)));
- }
- $this->tpl->setVariable("TXT_INSTRUCTIONS",
- nl2br(trim(ilUtil::shortenText(strip_tags($d["instruction"]), 200, true))));
-
- if ($d["mandatory"])
- {
- $this->tpl->setVariable("TXT_MANDATORY", $lng->txt("yes"));
- }
- else
- {
- $this->tpl->setVariable("TXT_MANDATORY", $lng->txt("no"));
- }
-
- $ilCtrl->setParameter($this->parent_obj, "ass_id", $d["id"]);
-
- if ($d["peer"])
- {
- $this->tpl->setVariable("TXT_PEER", $lng->txt("yes")." (".$d["peer_min"].")");
-
- if($d["peer_invalid"])
- {
- $this->tpl->setVariable("TXT_PEER_INVALID", $lng->txt("exc_peer_reviews_invalid_warning"));
- }
-
- if ($ass->afterDeadlineStrict()) // see #22246
- {
- $this->tpl->setVariable("TXT_PEER_OVERVIEW", $lng->txt("exc_peer_review_overview"));
- $this->tpl->setVariable("CMD_PEER_OVERVIEW",
- $ilCtrl->getLinkTargetByClass("ilexpeerreviewgui", "showPeerReviewOverview"));
- }
- }
- else
- {
- $this->tpl->setVariable("TXT_PEER", $lng->txt("no"));
- }
-
- $this->tpl->setVariable("TXT_TITLE", $d["title"]);
- $this->tpl->setVariable("TXT_TYPE", $d["type"]);
- $this->tpl->setVariable("ORDER_VAL", $d["order_val"]);
-
- $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit"));
- $this->tpl->setVariable("CMD_EDIT",
- $ilCtrl->getLinkTarget($this->parent_obj, "editAssignment"));
- }
+ if ($d["deadline"] > 0) {
+ $dl = ilDatePresentation::formatDate(new ilDateTime($d["deadline"], IL_CAL_UNIX));
+ if ($d["deadline2"] > 0) {
+ $dl .= "
(" . ilDatePresentation::formatDate(new ilDateTime($d["deadline2"], IL_CAL_UNIX)) . ")";
+ }
+ $this->tpl->setVariable("TXT_DEADLINE", $dl);
+ }
+ if ($d["start_time"] > 0) {
+ $this->tpl->setVariable(
+ "TXT_START_TIME",
+ ilDatePresentation::formatDate(new ilDateTime($d["start_time"], IL_CAL_UNIX))
+ );
+ }
+ $this->tpl->setVariable(
+ "TXT_INSTRUCTIONS",
+ nl2br(trim(ilUtil::shortenText(strip_tags($d["instruction"]), 200, true)))
+ );
+
+ if ($d["mandatory"]) {
+ $this->tpl->setVariable("TXT_MANDATORY", $lng->txt("yes"));
+ } else {
+ $this->tpl->setVariable("TXT_MANDATORY", $lng->txt("no"));
+ }
+
+ $ilCtrl->setParameter($this->parent_obj, "ass_id", $d["id"]);
+
+ if ($d["peer"]) {
+ $this->tpl->setVariable("TXT_PEER", $lng->txt("yes") . " (" . $d["peer_min"] . ")");
+
+ if ($d["peer_invalid"]) {
+ $this->tpl->setVariable("TXT_PEER_INVALID", $lng->txt("exc_peer_reviews_invalid_warning"));
+ }
+ if ($ass->afterDeadlineStrict()) { // see #22246
+ $this->tpl->setVariable("TXT_PEER_OVERVIEW", $lng->txt("exc_peer_review_overview"));
+ $this->tpl->setVariable(
+ "CMD_PEER_OVERVIEW",
+ $ilCtrl->getLinkTargetByClass("ilexpeerreviewgui", "showPeerReviewOverview")
+ );
+ }
+ } else {
+ $this->tpl->setVariable("TXT_PEER", $lng->txt("no"));
+ }
+
+ $this->tpl->setVariable("TXT_TITLE", $d["title"]);
+ $this->tpl->setVariable("TXT_TYPE", $d["type"]);
+ $this->tpl->setVariable("ORDER_VAL", $d["order_val"]);
+
+ $this->tpl->setVariable("TXT_EDIT", $lng->txt("edit"));
+ $this->tpl->setVariable(
+ "CMD_EDIT",
+ $ilCtrl->getLinkTarget($this->parent_obj, "editAssignment")
+ );
+ }
}
-?>
\ No newline at end of file
diff --git a/Modules/Exercise/classes/class.ilExAssignment.php b/Modules/Exercise/classes/class.ilExAssignment.php
index 5be8bdf99cb430f16818782f4433373c9a317af5..4865e212ed8643e57a06555562ed929fc4487cd3 100644
--- a/Modules/Exercise/classes/class.ilExAssignment.php
+++ b/Modules/Exercise/classes/class.ilExAssignment.php
@@ -10,2588 +10,2501 @@
*/
class ilExAssignment
{
- /**
- * @var ilDB
- */
- protected $db;
-
- /**
- * @var ilLanguage
- */
- protected $lng;
-
- /**
- * @var ilObjUser
- */
- protected $user;
-
- /**
- * @var ilAppEventHandler
- */
- protected $app_event_handler;
-
- /**
- * @deprecated direct checks against const should be avoided, use type objects instead
- */
- const TYPE_UPLOAD = 1;
- /**
- * @deprecated
- */
- const TYPE_BLOG = 2;
- /**
- * @deprecated
- */
- const TYPE_PORTFOLIO = 3;
- /**
- * @deprecated
- */
- const TYPE_UPLOAD_TEAM = 4;
- /**
- * @deprecated
- */
- const TYPE_TEXT = 5;
- /**
- * @deprecated
- */
- const TYPE_WIKI_TEAM = 6;
-
- const FEEDBACK_DATE_DEADLINE = 1;
- const FEEDBACK_DATE_SUBMISSION = 2;
- const FEEDBACK_DATE_CUSTOM = 3;
-
- const PEER_REVIEW_VALID_NONE = 1;
- const PEER_REVIEW_VALID_ONE = 2;
- const PEER_REVIEW_VALID_ALL = 3;
-
- const TEAMS_FORMED_BY_PARTICIPANTS = 0;
- const TEAMS_FORMED_BY_TUTOR = 1;
- const TEAMS_FORMED_BY_RANDOM = 2;
- const TEAMS_FORMED_BY_ASSIGNMENT = 3;
-
- const DEADLINE_ABSOLUTE = 0;
- const DEADLINE_RELATIVE = 1;
-
-
- protected $id;
- protected $exc_id;
- protected $type;
- protected $start_time;
- protected $deadline;
- protected $deadline2;
- protected $instruction;
- protected $title;
- protected $mandatory;
- protected $order_nr;
- protected $peer;
- protected $peer_min;
- protected $peer_unlock;
- protected $peer_dl;
- protected $peer_valid;
- protected $peer_file;
- protected $peer_personal;
- protected $peer_char;
- protected $peer_text;
- protected $peer_rating;
- protected $peer_crit_cat;
- protected $feedback_file;
- protected $feedback_cron;
- protected $feedback_date;
- protected $feedback_date_custom;
- protected $team_tutor = false;
- protected $max_file;
-
- protected $portfolio_template;
- protected $min_char_limit;
- protected $max_char_limit;
-
- protected $types = null;
-
- /**
- * @var ilExAssignmentTypeInterface
- */
- protected $ass_type;
-
- protected $deadline_mode = 0;
- protected $relative_deadline = 0;
- protected $starting_timestamp = null;
-
-
- protected $member_status = array(); // [array]
-
- protected $log;
-
- /**
- * Constructor
- */
- function __construct($a_id = 0)
- {
- global $DIC;
-
- $this->db = $DIC->database();
- $this->lng = $DIC->language();
- $this->user = $DIC->user();
- $this->app_event_handler = $DIC["ilAppEventHandler"];
- include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php");
- $this->types = ilExAssignmentTypes::getInstance();
-
- $this->setType(self::TYPE_UPLOAD);
- $this->setFeedbackDate(self::FEEDBACK_DATE_DEADLINE);
-
- $this->log = ilLoggerFactory::getLogger("exc");
-
- if ($a_id > 0)
- {
- $this->setId($a_id);
- $this->read();
- }
- }
-
- public static function getInstancesByExercise($a_exc_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $set = $ilDB->query("SELECT * FROM exc_assignment ".
- " WHERE exc_id = ".$ilDB->quote($a_exc_id, "integer").
- " ORDER BY order_nr ASC");
- $data = array();
-
- $order_val = 10;
- while ($rec = $ilDB->fetchAssoc($set))
- {
- // ???
- $rec["order_val"] = $order_val;
-
- $ass = new self();
- $ass->initFromDB($rec);
- $data[] = $ass;
-
- $order_val += 10;
- }
-
- return $data;
- }
-
- /**
- * @param array $a_file_data
- * @param integer $a_ass_id assignment id.
- * @return array
- */
- public static function instructionFileGetFileOrderData($a_file_data, $a_ass_id)
- {
- global $DIC;
-
- $db = $DIC->database();
- $db->setLimit(1,0);
-
- $result_order_val = $db->query("
+ /**
+ * @var ilDB
+ */
+ protected $db;
+
+ /**
+ * @var ilLanguage
+ */
+ protected $lng;
+
+ /**
+ * @var ilObjUser
+ */
+ protected $user;
+
+ /**
+ * @var ilAppEventHandler
+ */
+ protected $app_event_handler;
+
+ /**
+ * @deprecated direct checks against const should be avoided, use type objects instead
+ */
+ const TYPE_UPLOAD = 1;
+ /**
+ * @deprecated
+ */
+ const TYPE_BLOG = 2;
+ /**
+ * @deprecated
+ */
+ const TYPE_PORTFOLIO = 3;
+ /**
+ * @deprecated
+ */
+ const TYPE_UPLOAD_TEAM = 4;
+ /**
+ * @deprecated
+ */
+ const TYPE_TEXT = 5;
+ /**
+ * @deprecated
+ */
+ const TYPE_WIKI_TEAM = 6;
+
+ const FEEDBACK_DATE_DEADLINE = 1;
+ const FEEDBACK_DATE_SUBMISSION = 2;
+ const FEEDBACK_DATE_CUSTOM = 3;
+
+ const PEER_REVIEW_VALID_NONE = 1;
+ const PEER_REVIEW_VALID_ONE = 2;
+ const PEER_REVIEW_VALID_ALL = 3;
+
+ const TEAMS_FORMED_BY_PARTICIPANTS = 0;
+ const TEAMS_FORMED_BY_TUTOR = 1;
+ const TEAMS_FORMED_BY_RANDOM = 2;
+ const TEAMS_FORMED_BY_ASSIGNMENT = 3;
+
+ const DEADLINE_ABSOLUTE = 0;
+ const DEADLINE_RELATIVE = 1;
+
+
+ protected $id;
+ protected $exc_id;
+ protected $type;
+ protected $start_time;
+ protected $deadline;
+ protected $deadline2;
+ protected $instruction;
+ protected $title;
+ protected $mandatory;
+ protected $order_nr;
+ protected $peer;
+ protected $peer_min;
+ protected $peer_unlock;
+ protected $peer_dl;
+ protected $peer_valid;
+ protected $peer_file;
+ protected $peer_personal;
+ protected $peer_char;
+ protected $peer_text;
+ protected $peer_rating;
+ protected $peer_crit_cat;
+ protected $feedback_file;
+ protected $feedback_cron;
+ protected $feedback_date;
+ protected $feedback_date_custom;
+ protected $team_tutor = false;
+ protected $max_file;
+
+ protected $portfolio_template;
+ protected $min_char_limit;
+ protected $max_char_limit;
+
+ protected $types = null;
+
+ /**
+ * @var ilExAssignmentTypeInterface
+ */
+ protected $ass_type;
+
+ protected $deadline_mode = 0;
+ protected $relative_deadline = 0;
+ protected $starting_timestamp = null;
+
+
+ protected $member_status = array(); // [array]
+
+ protected $log;
+
+ /**
+ * Constructor
+ */
+ public function __construct($a_id = 0)
+ {
+ global $DIC;
+
+ $this->db = $DIC->database();
+ $this->lng = $DIC->language();
+ $this->user = $DIC->user();
+ $this->app_event_handler = $DIC["ilAppEventHandler"];
+ include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php");
+ $this->types = ilExAssignmentTypes::getInstance();
+
+ $this->setType(self::TYPE_UPLOAD);
+ $this->setFeedbackDate(self::FEEDBACK_DATE_DEADLINE);
+
+ $this->log = ilLoggerFactory::getLogger("exc");
+
+ if ($a_id > 0) {
+ $this->setId($a_id);
+ $this->read();
+ }
+ }
+
+ public static function getInstancesByExercise($a_exc_id)
+ {
+ global $DIC;
+
+ $ilDB = $DIC->database();
+
+ $set = $ilDB->query("SELECT * FROM exc_assignment " .
+ " WHERE exc_id = " . $ilDB->quote($a_exc_id, "integer") .
+ " ORDER BY order_nr ASC");
+ $data = array();
+
+ $order_val = 10;
+ while ($rec = $ilDB->fetchAssoc($set)) {
+ // ???
+ $rec["order_val"] = $order_val;
+
+ $ass = new self();
+ $ass->initFromDB($rec);
+ $data[] = $ass;
+
+ $order_val += 10;
+ }
+
+ return $data;
+ }
+
+ /**
+ * @param array $a_file_data
+ * @param integer $a_ass_id assignment id.
+ * @return array
+ */
+ public static function instructionFileGetFileOrderData($a_file_data, $a_ass_id)
+ {
+ global $DIC;
+
+ $db = $DIC->database();
+ $db->setLimit(1, 0);
+
+ $result_order_val = $db->query("
SELECT id, order_nr
FROM exc_ass_file_order
WHERE assignment_id = {$db->quote($a_ass_id, 'integer')}
AND filename = {$db->quote($a_file_data['entry'], 'string')}
");
- $order_val = 0;
- $order_id = 0;
- while ($row = $db->fetchAssoc($result_order_val)) {
- $order_val = (int)$row['order_nr'];
- $order_id = (int)$row['id'];
- }
- return array($order_val, $order_id);
- }
-
- public function hasTeam()
- {
- return $this->ass_type->usesTeams();
- }
-
- /**
- * Set assignment id
- *
- * @param int assignment id
- */
- function setId($a_val)
- {
- $this->id = $a_val;
- }
-
- /**
- * Get assignment id
- *
- * @return int assignment id
- */
- function getId()
- {
- return $this->id;
- }
-
- /**
- * Set exercise id
- *
- * @param int exercise id
- */
- function setExerciseId($a_val)
- {
- $this->exc_id = $a_val;
- }
-
- /**
- * Get exercise id
- *
- * @return int exercise id
- */
- function getExerciseId()
- {
- return $this->exc_id;
- }
-
- /**
- * Set start time (timestamp)
- *
- * @param int start time (timestamp)
- */
- function setStartTime($a_val)
- {
- $this->start_time = $a_val;
- }
-
- /**
- * Get start time (timestamp)
- *
- * @return int start time (timestamp)
- */
- function getStartTime()
- {
- return $this->start_time;
- }
-
- /**
- * Set deadline (timestamp)
- *
- * @param int deadline (timestamp)
- */
- function setDeadline($a_val)
- {
- $this->deadline = $a_val;
- }
-
- /**
- * Get deadline (timestamp)
- *
- * @return int deadline (timestamp)
- */
- function getDeadline()
- {
- return $this->deadline;
- }
-
- /**
- * Set deadline mode
- *
- * @param int $a_val deadline mode
- */
- function setDeadlineMode($a_val)
- {
- $this->deadline_mode = $a_val;
- }
-
- /**
- * Get deadline mode
- *
- * @return int deadline mode
- */
- function getDeadlineMode()
- {
- return $this->deadline_mode;
- }
-
- /**
- * Set relative deadline
- *
- * @param int $a_val relative deadline
- */
- function setRelativeDeadline($a_val)
- {
- $this->relative_deadline = $a_val;
- }
-
- /**
- * Get relative deadline
- *
- * @return int relative deadline
- */
- function getRelativeDeadline()
- {
- return $this->relative_deadline;
- }
-
- /**
- * Get individual deadline (max of common or idl (team) deadline = Official Deadline)
- * @param int $a_user_id
- * @return int
- */
- function getPersonalDeadline($a_user_id)
- {
- $ilDB = $this->db;
-
- $is_team = false;
- if($this->ass_type->usesTeams())
- {
- include_once("./Modules/Exercise/classes/class.ilExAssignmentTeam.php");
- $team_id = ilExAssignmentTeam::getTeamId($this->getId(), $a_user_id);
- if(!$team_id)
- {
- // #0021043
- return $this->getDeadline();
- }
- $a_user_id = $team_id;
- $is_team = true;
- }
-
- $set = $ilDB->query("SELECT tstamp FROM exc_idl".
- " WHERE ass_id = ".$ilDB->quote($this->getId(), "integer").
- " AND member_id = ".$ilDB->quote($a_user_id, "integer").
- " AND is_team = ".$ilDB->quote($is_team, "integer"));
- $row = $ilDB->fetchAssoc($set);
-
- // use assignment deadline if no direct personal
- return max($row["tstamp"], $this->getDeadline());
- }
-
- /**
- * Get last/final personal deadline (of assignment)
- *
- * @return int
- */
- public function getLastPersonalDeadline()
- {
- $ilDB = $this->db;
-
- $set = $ilDB->query("SELECT MAX(tstamp) FROM exc_idl".
- " WHERE ass_id = ".$ilDB->quote($this->getId(), "integer"));
- $row = $ilDB->fetchAssoc($set);
- return $row["tstamp"];
- }
-
- /**
- * Set extended deadline (timestamp)
- *
- * @param int
- */
- function setExtendedDeadline($a_val)
- {
- if($a_val !== null)
- {
- $a_val = (int)$a_val;
- }
- $this->deadline2 = $a_val;
- }
-
- /**
- * Get extended deadline (timestamp)
- *
- * @return int
- */
- function getExtendedDeadline()
- {
- return $this->deadline2;
- }
-
- /**
- * Set instruction
- *
- * @param string instruction
- */
- function setInstruction($a_val)
- {
- $this->instruction = $a_val;
- }
-
- /**
- * Get instruction
- *
- * @return string instruction
- */
- function getInstruction()
- {
- return $this->instruction;
- }
-
- /**
- * Set title
- *
- * @param string title
- */
- function setTitle($a_val)
- {
- $this->title = $a_val;
- }
-
- /**
- * Get title
- *
- * @return string title
- */
- function getTitle()
- {
- return $this->title;
- }
-
- /**
- * Set mandatory
- *
- * @param int mandatory
- */
- function setMandatory($a_val)
- {
- $this->mandatory = $a_val;
- }
-
- /**
- * Get mandatory
- *
- * @return int mandatory
- */
- function getMandatory()
- {
- return $this->mandatory;
- }
-
- /**
- * Set order nr
- *
- * @param int order nr
- */
- function setOrderNr($a_val)
- {
- $this->order_nr = $a_val;
- }
-
- /**
- * Get order nr
- *
- * @return int order nr
- */
- function getOrderNr()
- {
- return $this->order_nr;
- }
-
- /**
- * Set type
- *
- * @param int $a_value
- * @deprecated this will most probably become an non public function in the future (or become obsolete)
- */
- function setType($a_value)
- {
- if($this->isValidType($a_value))
- {
- $this->type = (int)$a_value;
-
- $this->ass_type = $this->types->getById($a_value);
-
- if($this->ass_type->usesTeams())
- {
- $this->setPeerReview(false);
- }
- }
- }
-
- /**
- * Get assignment type
- *
- * @param
- * @return null|ilExAssignmentTypeInterface
- */
- public function getAssignmentType()
- {
- return $this->ass_type;
- }
-
-
- /**
- * Get type
- *
- * @return int
- * @deprecated this will most probably become an non public function in the future (or become obsolete)
- */
- function getType()
- {
- return $this->type;
- }
-
- /**
- * Is given type valid?
- *
- * @param int $a_value
- * @return bool
- */
- function isValidType($a_value)
- {
- return $this->types->isValidId($a_value);
- }
-
- /**
- * Toggle peer review
- *
- * @param bool $a_value
- */
- function setPeerReview($a_value)
- {
- $this->peer = (bool)$a_value;
- }
-
- /**
- * Get peer review status
- *
- * @return bool
- */
- function getPeerReview()
- {
- return (bool)$this->peer;
- }
-
- /**
- * Set peer review minimum
- *
- * @param int $a_value
- */
- function setPeerReviewMin($a_value)
- {
- $this->peer_min = (int)$a_value;
- }
-
- /**
- * Get peer review minimum
- *
- * @return int
- */
- function getPeerReviewMin()
- {
- return (int)$this->peer_min;
- }
-
- /**
- * Set peer review simple unlock
- *
- * @param bool $a_value
- */
- function setPeerReviewSimpleUnlock($a_value)
- {
- $this->peer_unlock = (bool)$a_value;
- }
-
- /**
- * Get peer review simple unlock
- *
- * @return bool
- */
- function getPeerReviewSimpleUnlock()
- {
- return (bool)$this->peer_unlock;
- }
-
- /**
- * Set peer review deadline (timestamp)
- *
- * @param int deadline (timestamp)
- */
- function setPeerReviewDeadline($a_val)
- {
- $this->peer_dl = $a_val;
- }
-
- /**
- * Get peer review deadline (timestamp)
- *
- * @return int deadline (timestamp)
- */
- function getPeerReviewDeadline()
- {
- return $this->peer_dl;
- }
-
- /**
- * Set peer review validation
- *
- * @param int $a_value
- */
- function setPeerReviewValid($a_value)
- {
- $this->peer_valid = (int)$a_value;
- }
-
- /**
- * Get peer review validatiob
- *
- * @return int
- */
- function getPeerReviewValid()
- {
- return (int)$this->peer_valid;
- }
-
- /**
- * Set peer review rating
- *
- * @param bool
- */
- function setPeerReviewRating($a_val)
- {
- $this->peer_rating = (bool)$a_val;
- }
-
- /**
- * Get peer review rating status
- *
- * @return bool
- */
- function hasPeerReviewRating()
- {
- return $this->peer_rating;
- }
-
- /**
- * Set peer review text
- *
- * @param bool
- */
- function setPeerReviewText($a_val)
- {
- $this->peer_text = (bool)$a_val;
- }
-
- /**
- * Get peer review text status
- *
- * @return bool
- */
- function hasPeerReviewText()
- {
- return $this->peer_text;
- }
-
- /**
- * Set peer review file upload
- *
- * @param bool
- */
- function setPeerReviewFileUpload($a_val)
- {
- $this->peer_file = (bool)$a_val;
- }
-
- /**
- * Get peer review file upload status
- *
- * @return bool
- */
- function hasPeerReviewFileUpload()
- {
- return $this->peer_file;
- }
-
- /**
- * Set peer review personalized
- *
- * @param bool
- */
- function setPeerReviewPersonalized($a_val)
- {
- $this->peer_personal = (bool)$a_val;
- }
-
- /**
- * Get peer review personalized status
- *
- * @return bool
- */
- function hasPeerReviewPersonalized()
- {
- return $this->peer_personal;
- }
-
- /**
- * Set peer review minimum characters
- *
- * @param int $a_value
- */
- function setPeerReviewChars($a_value)
- {
- $a_value = (is_numeric($a_value) && (int)$a_value > 0)
- ? (int)$a_value
- : null;
- $this->peer_char = $a_value;
- }
-
- /**
- * Get peer review minimum characters
- *
- * @return int
- */
- function getPeerReviewChars()
- {
- return $this->peer_char;
- }
-
- /**
- * Set peer review criteria catalogue id
- *
- * @param int $a_value
- */
- function setPeerReviewCriteriaCatalogue($a_value)
- {
- $a_value = is_numeric($a_value)
- ? (int)$a_value
- : null;
- $this->crit_cat = $a_value;
- }
-
- /**
- * Get peer review criteria catalogue id
- *
- * @return int
- */
- function getPeerReviewCriteriaCatalogue()
- {
- return $this->crit_cat;
- }
-
- function getPeerReviewCriteriaCatalogueItems()
- {
- include_once "Modules/Exercise/classes/class.ilExcCriteria.php";
-
- if($this->crit_cat)
- {
- return ilExcCriteria::getInstancesByParentId($this->crit_cat);
- }
- else
- {
- $res = array();
-
- if($this->peer_rating)
- {
- $res[] = ilExcCriteria::getInstanceByType("rating");
- }
-
- if($this->peer_text)
- {
- $crit = ilExcCriteria::getInstanceByType("text");
- if($this->peer_char)
- {
- $crit->setMinChars($this->peer_char);
- }
- $res[] = $crit;
- }
-
- if($this->peer_file)
- {
- $res[] = ilExcCriteria::getInstanceByType("file");
- }
-
- return $res;
- }
- }
-
- /**
- * Set (global) feedback file
- *
- * @param string $a_value
- */
- function setFeedbackFile($a_value)
- {
- $this->feedback_file = (string)$a_value;
- }
-
- /**
- * Get (global) feedback file
- *
- * @return int
- */
- function getFeedbackFile()
- {
- return (string)$this->feedback_file;
- }
-
- /**
- * Toggle (global) feedback file cron
- *
- * @param bool $a_value
- */
- function setFeedbackCron($a_value)
- {
- $this->feedback_cron = (string)$a_value;
- }
-
- /**
- * Get (global) feedback file cron status
- *
- * @return int
- */
- function hasFeedbackCron()
- {
- return (bool)$this->feedback_cron;
- }
-
- /**
- * Set (global) feedback file availability date
- *
- * @param int $a_value
- */
- function setFeedbackDate($a_value)
- {
- $this->feedback_date = (int)$a_value;
- }
-
- /**
- * Get (global) feedback file availability date
- *
- * @return int
- */
- function getFeedbackDate()
- {
- return (int)$this->feedback_date;
- }
-
- /**
- * Set (global) feedback file availability using a custom date.
- * @param int $a_value timestamp
- */
- function setFeedbackDateCustom($a_value)
- {
- $this->feedback_date_custom = $a_value;
- }
-
- /**
- * Get feedback file availability using custom date.
- * @return string timestamp
- */
- function getFeedbackDateCustom()
- {
- return $this->feedback_date_custom;
- }
-
- /**
- * Set team management by tutor
- *
- * @param bool $a_value
- */
- function setTeamTutor($a_value)
- {
- $this->team_tutor = (bool)$a_value;
- }
-
- /**
- * Get team management by tutor
- *
- * @return bool
- */
- function getTeamTutor()
- {
- return $this->team_tutor;
- }
-
- /**
- * Set max number of uploads
- *
- * @param int $a_value
- */
- function setMaxFile($a_value)
- {
- if($a_value !== null)
- {
- $a_value = (int)$a_value;
- }
- $this->max_file = $a_value;
- }
-
- /**
- * Get max number of uploads
- *
- * @return bool
- */
- function getMaxFile()
- {
- return $this->max_file;
- }
-
- /**
- * Set portfolio template id
- *
- * @param int $a_val
- */
- function setPortfolioTemplateId($a_val)
- {
- $this->portfolio_template = $a_val;
- }
-
- /**
- * Get portfolio template id
- *
- * @return int portfolio template id
- */
- function getPortfolioTemplateId()
- {
- return $this->portfolio_template;
- }
-
-
- /**
- * Read from db
- */
- function read()
- {
- $ilDB = $this->db;
-
- $set = $ilDB->query("SELECT * FROM exc_assignment ".
- " WHERE id = ".$ilDB->quote($this->getId(), "integer")
- );
- $rec = $ilDB->fetchAssoc($set);
-
- // #16172 - might be deleted
- if(is_array($rec))
- {
- $this->initFromDB($rec);
- }
- }
-
- /**
- * Import DB record
- *
- * @see getInstancesByExercise()
- * @param array $a_set
- */
- protected function initFromDB(array $a_set)
- {
- $this->setId($a_set["id"]);
- $this->setExerciseId($a_set["exc_id"]);
- $this->setDeadline($a_set["time_stamp"]);
- $this->setExtendedDeadline($a_set["deadline2"]);
- $this->setInstruction($a_set["instruction"]);
- $this->setTitle($a_set["title"]);
- $this->setStartTime($a_set["start_time"]);
- $this->setOrderNr($a_set["order_nr"]);
- $this->setMandatory($a_set["mandatory"]);
- $this->setType($a_set["type"]);
- $this->setPeerReview($a_set["peer"]);
- $this->setPeerReviewMin($a_set["peer_min"]);
- $this->setPeerReviewSimpleUnlock($a_set["peer_unlock"]);
- $this->setPeerReviewDeadline($a_set["peer_dl"]);
- $this->setPeerReviewValid($a_set["peer_valid"]);
- $this->setPeerReviewFileUpload($a_set["peer_file"]);
- $this->setPeerReviewPersonalized($a_set["peer_prsl"]);
- $this->setPeerReviewChars($a_set["peer_char"]);
- $this->setPeerReviewText($a_set["peer_text"]);
- $this->setPeerReviewRating($a_set["peer_rating"]);
- $this->setPeerReviewCriteriaCatalogue($a_set["peer_crit_cat"]);
- $this->setFeedbackFile($a_set["fb_file"]);
- $this->setFeedbackDate($a_set["fb_date"]);
- $this->setFeedbackDateCustom($a_set["fb_date_custom"]);
- $this->setFeedbackCron($a_set["fb_cron"]);
- $this->setTeamTutor($a_set["team_tutor"]);
- $this->setMaxFile($a_set["max_file"]);
- $this->setPortfolioTemplateId($a_set["portfolio_template"]);
- $this->setMinCharLimit($a_set["min_char_limit"]);
- $this->setMaxCharLimit($a_set["max_char_limit"]);
- $this->setDeadlineMode($a_set["deadline_mode"]);
- $this->setRelativeDeadline($a_set["relative_deadline"]);
- }
-
- /**
- * Save assignment
- */
- function save()
- {
- $ilDB = $this->db;
-
- if ($this->getOrderNr() == 0)
- {
- $this->setOrderNr(
- self::lookupMaxOrderNrForEx($this->getExerciseId())
- + 10);
- }
-
- $next_id = $ilDB->nextId("exc_assignment");
- $ilDB->insert("exc_assignment", array(
- "id" => array("integer", $next_id),
- "exc_id" => array("integer", $this->getExerciseId()),
- "time_stamp" => array("integer", $this->getDeadline()),
- "deadline2" => array("integer", $this->getExtendedDeadline()),
- "instruction" => array("clob", $this->getInstruction()),
- "title" => array("text", $this->getTitle()),
- "start_time" => array("integer", $this->getStartTime()),
- "order_nr" => array("integer", $this->getOrderNr()),
- "mandatory" => array("integer", $this->getMandatory()),
- "type" => array("integer", $this->getType()),
- "peer" => array("integer", $this->getPeerReview()),
- "peer_min" => array("integer", $this->getPeerReviewMin()),
- "peer_unlock" => array("integer", $this->getPeerReviewSimpleUnlock()),
- "peer_dl" => array("integer", $this->getPeerReviewDeadline()),
- "peer_valid" => array("integer", $this->getPeerReviewValid()),
- "peer_file" => array("integer", $this->hasPeerReviewFileUpload()),
- "peer_prsl" => array("integer", $this->hasPeerReviewPersonalized()),
- "peer_char" => array("integer", $this->getPeerReviewChars()),
- "peer_text" => array("integer", (int) $this->hasPeerReviewText()),
- "peer_rating" => array("integer", (int) $this->hasPeerReviewRating()),
- "peer_crit_cat" => array("integer", $this->getPeerReviewCriteriaCatalogue()),
- "fb_file" => array("text", $this->getFeedbackFile()),
- "fb_date" => array("integer", $this->getFeedbackDate()),
- "fb_date_custom" => array("integer", $this->getFeedbackDateCustom()),
- "fb_cron" => array("integer", $this->hasFeedbackCron()),
- "team_tutor" => array("integer", $this->getTeamTutor()),
- "max_file" => array("integer", $this->getMaxFile()),
- "portfolio_template" => array("integer", $this->getPortFolioTemplateId()),
- "min_char_limit" => array("integer", $this->getMinCharLimit()),
- "max_char_limit" => array("integer", $this->getMaxCharLimit()),
- "relative_deadline" => array("integer", $this->getRelativeDeadline()),
- "deadline_mode" => array("integer", $this->getDeadlineMode())
- ));
- $this->setId($next_id);
- $exc = new ilObjExercise($this->getExerciseId(), false);
- $exc->updateAllUsersStatus();
- self::createNewAssignmentRecords($next_id, $exc);
-
- $this->handleCalendarEntries("create");
- }
-
- /**
- * Update
- */
- function update()
- {
- $ilDB = $this->db;
-
- $ilDB->update("exc_assignment",
- array(
- "exc_id" => array("integer", $this->getExerciseId()),
- "time_stamp" => array("integer", $this->getDeadline()),
- "deadline2" => array("integer", $this->getExtendedDeadline()),
- "instruction" => array("clob", $this->getInstruction()),
- "title" => array("text", $this->getTitle()),
- "start_time" => array("integer", $this->getStartTime()),
- "order_nr" => array("integer", $this->getOrderNr()),
- "mandatory" => array("integer", $this->getMandatory()),
- "type" => array("integer", $this->getType()),
- "peer" => array("integer", $this->getPeerReview()),
- "peer_min" => array("integer", $this->getPeerReviewMin()),
- "peer_unlock" => array("integer", $this->getPeerReviewSimpleUnlock()),
- "peer_dl" => array("integer", $this->getPeerReviewDeadline()),
- "peer_valid" => array("integer", $this->getPeerReviewValid()),
- "peer_file" => array("integer", $this->hasPeerReviewFileUpload()),
- "peer_prsl" => array("integer", $this->hasPeerReviewPersonalized()),
- "peer_char" => array("integer", $this->getPeerReviewChars()),
- "peer_text" => array("integer", (int) $this->hasPeerReviewText()),
- "peer_rating" => array("integer", (int) $this->hasPeerReviewRating()),
- "peer_crit_cat" => array("integer", $this->getPeerReviewCriteriaCatalogue()),
- "fb_file" => array("text", $this->getFeedbackFile()),
- "fb_date" => array("integer", $this->getFeedbackDate()),
- "fb_date_custom" => array("integer", $this->getFeedbackDateCustom()),
- "fb_cron" => array("integer", $this->hasFeedbackCron()),
- "team_tutor" => array("integer", $this->getTeamTutor()),
- "max_file" => array("integer", $this->getMaxFile()),
- "portfolio_template" => array("integer", $this->getPortFolioTemplateId()),
- "min_char_limit" => array("integer", $this->getMinCharLimit()),
- "max_char_limit" => array("integer", $this->getMaxCharLimit()),
- "deadline_mode" => array("integer", $this->getDeadlineMode()),
- "relative_deadline" => array("integer", $this->getRelativeDeadline())
- ),
- array(
- "id" => array("integer", $this->getId()),
- ));
- $exc = new ilObjExercise($this->getExerciseId(), false);
- $exc->updateAllUsersStatus();
-
- $this->handleCalendarEntries("update");
- }
-
- /**
- * Delete assignment
- */
- function delete()
- {
- $ilDB = $this->db;
-
- $this->deleteGlobalFeedbackFile();
-
- $ilDB->manipulate("DELETE FROM exc_assignment WHERE ".
- " id = ".$ilDB->quote($this->getId(), "integer")
- );
- $exc = new ilObjExercise($this->getExerciseId(), false);
- $exc->updateAllUsersStatus();
-
- $this->handleCalendarEntries("delete");
-
- $reminder = new ilExAssignmentReminder();
- $reminder->deleteReminders($this->getId());
- }
-
-
- /**
- * Get assignments data of an exercise in an array
- */
- static function getAssignmentDataOfExercise($a_exc_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- // should be changed to self::getInstancesByExerciseId()
-
- $set = $ilDB->query("SELECT * FROM exc_assignment ".
- " WHERE exc_id = ".$ilDB->quote($a_exc_id, "integer").
- " ORDER BY order_nr ASC");
- $data = array();
-
- $order_val = 10;
- while ($rec = $ilDB->fetchAssoc($set))
- {
-
- $data[] = array(
- "id" => $rec["id"],
- "exc_id" => $rec["exc_id"],
- "deadline" => $rec["time_stamp"],
- "deadline2" => $rec["deadline2"],
- "instruction" => $rec["instruction"],
- "title" => $rec["title"],
- "start_time" => $rec["start_time"],
- "order_val" => $order_val,
- "mandatory" => $rec["mandatory"],
- "type" => $rec["type"],
- "peer" => $rec["peer"],
- "peer_min" => $rec["peer_min"],
- "peer_dl" => $rec["peer_dl"],
- "peer_file" => $rec["peer_file"],
- "peer_prsl" => $rec["peer_prsl"],
- "fb_file" => $rec["fb_file"],
- "fb_date" => $rec["fb_date"],
- "fb_cron" => $rec["fb_cron"],
- "deadline_mode" => $rec["deadline_mode"],
- "relative_deadline" => $rec["relative_deadline"]
- );
- $order_val += 10;
- }
- return $data;
- }
-
- /**
- * Clone assignments of exercise
- * @param
- * @return
- */
- static function cloneAssignmentsOfExercise($a_old_exc_id, $a_new_exc_id, array $a_crit_cat_map)
- {
- $ass_data = self::getInstancesByExercise($a_old_exc_id);
- foreach ($ass_data as $d)
- {
- // clone assignment
- $new_ass = new ilExAssignment();
- $new_ass->setExerciseId($a_new_exc_id);
- $new_ass->setTitle($d->getTitle());
- $new_ass->setDeadline($d->getDeadline());
- $new_ass->setExtendedDeadline($d->getExtendedDeadline());
- $new_ass->setInstruction($d->getInstruction());
- $new_ass->setMandatory($d->getMandatory());
- $new_ass->setOrderNr($d->getOrderNr());
- $new_ass->setStartTime($d->getStartTime());
- $new_ass->setType($d->getType());
- $new_ass->setPeerReview($d->getPeerReview());
- $new_ass->setPeerReviewMin($d->getPeerReviewMin());
- $new_ass->setPeerReviewDeadline($d->getPeerReviewDeadline());
- $new_ass->setPeerReviewFileUpload($d->hasPeerReviewFileUpload());
- $new_ass->setPeerReviewPersonalized($d->hasPeerReviewPersonalized());
- $new_ass->setPeerReviewValid($d->getPeerReviewValid());
- $new_ass->setPeerReviewChars($d->getPeerReviewChars());
- $new_ass->setPeerReviewText($d->hasPeerReviewText());
- $new_ass->setPeerReviewRating($d->hasPeerReviewRating());
- $new_ass->setPeerReviewCriteriaCatalogue($d->getPeerReviewCriteriaCatalogue());
- $new_ass->setPeerReviewSimpleUnlock($d->getPeerReviewSimpleUnlock());
- $new_ass->setFeedbackFile($d->getFeedbackFile());
- $new_ass->setFeedbackDate($d->getFeedbackDate());
- $new_ass->setFeedbackDateCustom($d->getFeedbackDateCustom());
- $new_ass->setFeedbackCron($d->hasFeedbackCron()); // #16295
- $new_ass->setTeamTutor($d->getTeamTutor());
- $new_ass->setMaxFile($d->getMaxFile());
- $new_ass->setMinCharLimit($d->getMinCharLimit());
- $new_ass->setMaxCharLimit($d->getMaxCharLimit());
- $new_ass->setPortfolioTemplateId($d->getPortfolioTemplateId());
- $new_ass->setDeadlineMode($d->getDeadlineMode());
- $new_ass->setRelativeDeadline($d->getRelativeDeadline());
-
- // criteria catalogue(s)
- if($d->getPeerReviewCriteriaCatalogue() &&
- array_key_exists($d->getPeerReviewCriteriaCatalogue(), $a_crit_cat_map))
- {
- $new_ass->setPeerReviewCriteriaCatalogue($a_crit_cat_map[$d->getPeerReviewCriteriaCatalogue()]);
- }
-
- $new_ass->save();
-
-
- // clone assignment files
- include_once("./Modules/Exercise/classes/class.ilFSWebStorageExercise.php");
- $old_web_storage = new ilFSWebStorageExercise($a_old_exc_id, (int) $d->getId());
- $new_web_storage = new ilFSWebStorageExercise($a_new_exc_id, (int) $new_ass->getId());
- $new_web_storage->create();
- if (is_dir($old_web_storage->getPath()))
- {
- ilUtil::rCopy($old_web_storage->getPath(), $new_web_storage->getPath());
- }
-
- // clone global feedback file
- include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php");
- $old_storage = new ilFSStorageExercise($a_old_exc_id, (int) $d->getId());
- $new_storage = new ilFSStorageExercise($a_new_exc_id, (int) $new_ass->getId());
- $new_storage->create();
- if (is_dir($old_storage->getGlobalFeedbackPath()))
- {
- ilUtil::rCopy($old_storage->getGlobalFeedbackPath(), $new_storage->getGlobalFeedbackPath());
- }
-
- // type specific properties
- $ass_type = $d->getAssignmentType();
- $ass_type->cloneSpecificProperties($d, $new_ass);
- }
- }
-
- /**
- * Get files
- */
- public function getFiles()
- {
- $this->log->debug("getting files from class.ilExAssignment using ilFSWebStorageExercise");
- include_once("./Modules/Exercise/classes/class.ilFSWebStorageExercise.php");
- $storage = new ilFSWebStorageExercise($this->getExerciseId(), $this->getId());
- return $storage->getFiles();
- }
-
- /**
- * @param $a_ass_id
- * @return array
- */
- public function getInstructionFilesOrder()
- {
- $ilDB = $this->db;
-
- $set = $ilDB->query("SELECT filename, order_nr, id FROM exc_ass_file_order ".
- " WHERE assignment_id = ".$ilDB->quote($this->getId(), "integer")
- );
-
- $data = array();
- while ($rec = $ilDB->fetchAssoc($set))
- {
- $data[$rec['filename']] = $rec;
- }
-
- return $data;
- }
-
- /**
- * Select the maximum order nr for an exercise
- */
- static function lookupMaxOrderNrForEx($a_exc_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $set = $ilDB->query("SELECT MAX(order_nr) mnr FROM exc_assignment ".
- " WHERE exc_id = ".$ilDB->quote($a_exc_id, "integer")
- );
- while ($rec = $ilDB->fetchAssoc($set))
- {
- return (int) $rec["mnr"];
- }
- return 0;
- }
-
- /**
- * Check if assignment is online
- * @param int $a_ass_id
- * @return bool
- */
- public static function lookupAssignmentOnline($a_ass_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $query = "SELECT id FROM exc_assignment ".
- "WHERE start_time <= ".$ilDB->quote(time(),'integer').' '.
- "AND time_stamp >= ".$ilDB->quote(time(),'integer').' '.
- "AND id = ".$ilDB->quote($a_ass_id,'integer');
- $res = $ilDB->query($query);
-
- return $res->numRows() ? true : false;
- }
-
- /**
- * Lookup excercise id for assignment id
- *
- * @param int $a_ass_id
- * @return int
- */
- public static function lookupExerciseId($a_ass_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $query = "SELECT exc_id FROM exc_assignment ".
- "WHERE id = ".$ilDB->quote($a_ass_id,'integer');
- $res = $ilDB->fetchAssoc($ilDB->query($query));
-
- return (int) $res["exc_id"];
- }
-
- /**
- * Private lookup
- */
- private static function lookup($a_id, $a_field)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $set = $ilDB->query("SELECT ".$a_field." FROM exc_assignment ".
- " WHERE id = ".$ilDB->quote($a_id, "integer")
- );
-
- $rec = $ilDB->fetchAssoc($set);
-
- return $rec[$a_field];
- }
-
- /**
- * Lookup title
- */
- static function lookupTitle($a_id)
- {
- return self::lookup($a_id, "title");
- }
-
- /**
- * Lookup type
- */
- static function lookupType($a_id)
- {
- return self::lookup($a_id, "type");
- }
-
- /**
- * Save ordering of all assignments of an exercise
- */
- static function saveAssOrderOfExercise($a_ex_id, $a_order)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $result_order = array();
- asort($a_order);
- $nr = 10;
- foreach ($a_order as $k => $v)
- {
- // the check for exc_id is for security reasons. ass ids are unique.
- $ilDB->manipulate($t = "UPDATE exc_assignment SET ".
- " order_nr = ".$ilDB->quote($nr, "integer").
- " WHERE id = ".$ilDB->quote((int) $k, "integer").
- " AND exc_id = ".$ilDB->quote((int) $a_ex_id, "integer")
- );
- $nr+=10;
- }
- }
-
- /**
- * Order assignments by deadline date
- */
- static function orderAssByDeadline($a_ex_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $set = $ilDB->query("SELECT id FROM exc_assignment ".
- " WHERE exc_id = ".$ilDB->quote($a_ex_id, "integer").
- " ORDER BY time_stamp ASC"
- );
- $nr = 10;
- while ($rec = $ilDB->fetchAssoc($set))
- {
- $ilDB->manipulate("UPDATE exc_assignment SET ".
- " order_nr = ".$ilDB->quote($nr, "integer").
- " WHERE id = ".$ilDB->quote($rec["id"], "integer")
- );
- $nr += 10;
- }
- }
-
- /**
- * Order assignments by deadline date
- */
- static function countMandatory($a_ex_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $set = $ilDB->query("SELECT count(*) cntm FROM exc_assignment ".
- " WHERE exc_id = ".$ilDB->quote($a_ex_id, "integer").
- " AND mandatory = ".$ilDB->quote(1, "integer")
- );
- $rec = $ilDB->fetchAssoc($set);
- return $rec["cntm"];
- }
-
-///
- /**
- * Check whether student has upload new files after tutor has
- * set the exercise to another than notgraded.
- */
- static function lookupUpdatedSubmission($ass_id, $member_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
- $lng = $DIC->language();
-
- // team upload?
- $user_ids = self::getTeamMembersByAssignmentId($ass_id, $member_id);
- if(!$user_ids)
- {
- $user_ids = array($member_id);
- }
-
- $q="SELECT exc_mem_ass_status.status_time, exc_returned.ts ".
- "FROM exc_mem_ass_status, exc_returned ".
- "WHERE exc_mem_ass_status.status_time < exc_returned.ts ".
- "AND NOT exc_mem_ass_status.status_time IS NULL ".
- "AND exc_returned.ass_id = exc_mem_ass_status.ass_id ".
- "AND exc_returned.user_id = exc_mem_ass_status.usr_id ".
- "AND exc_returned.ass_id=".$ilDB->quote($ass_id, "integer").
- " AND ".$ilDB->in("exc_returned.user_id", $user_ids, "", "integer");
-
- $usr_set = $ilDB->query($q);
-
- $array = $ilDB->fetchAssoc($usr_set);
-
- if (count($array)==0)
- {
- return 0;
- }
- else
- {
- return 1;
- }
-
- }
-
- /**
- * get member list data
- */
- function getMemberListData()
- {
- $ilDB = $this->db;
-
- $mem = array();
-
- // first get list of members from member table
- $set = $ilDB->query("SELECT ud.usr_id, ud.lastname, ud.firstname, ud.login".
- " FROM exc_members excm".
- " JOIN usr_data ud ON (ud.usr_id = excm.usr_id)".
- " WHERE excm.obj_id = ".$ilDB->quote($this->getExerciseId(), "integer"));
- while($rec = $ilDB->fetchAssoc($set))
- {
- $mem[$rec["usr_id"]] =
- array(
- "name" => $rec["lastname"].", ".$rec["firstname"],
- "login" => $rec["login"],
- "usr_id" => $rec["usr_id"],
- "lastname" => $rec["lastname"],
- "firstname" => $rec["firstname"]
- );
- }
-
- include_once "Modules/Exercise/classes/class.ilExSubmission.php";
-
- $q = "SELECT * FROM exc_mem_ass_status ".
- "WHERE ass_id = ".$ilDB->quote($this->getId(), "integer");
- $set = $ilDB->query($q);
- while($rec = $ilDB->fetchAssoc($set))
- {
- if (isset($mem[$rec["usr_id"]]))
- {
- $sub = new ilExSubmission($this, $rec["usr_id"]);
-
- $mem[$rec["usr_id"]]["sent_time"] = $rec["sent_time"];
- $mem[$rec["usr_id"]]["submission"] = $sub->getLastSubmission();
- $mem[$rec["usr_id"]]["status_time"] = $rec["status_time"];
- $mem[$rec["usr_id"]]["feedback_time"] = $rec["feedback_time"];
- $mem[$rec["usr_id"]]["notice"] = $rec["notice"];
- $mem[$rec["usr_id"]]["status"] = $rec["status"];
- $mem[$rec["usr_id"]]["mark"] = $rec["mark"];
- $mem[$rec["usr_id"]]["comment"] = $rec["u_comment"];
- }
- }
- return $mem;
- }
-
- /**
- * Get submission data for an specific user,exercise and assignment.
- * todo we can refactor a bit the method getMemberListData to use this and remove duplicate code.
- * @param $a_user_id
- * @param $a_grade
- * @return array
- */
- public function getExerciseMemberAssignmentData($a_user_id, $a_grade = "")
- {
- global $DIC;
- $ilDB = $DIC->database();
-
- include_once "Modules/Exercise/classes/class.ilExSubmission.php";
-
- if(in_array($a_grade, array("notgraded", "passed", "failed")))
- {
- $and_grade = " AND status = ".$ilDB->quote($a_grade, "text");
- }
-
- $q = "SELECT * FROM exc_mem_ass_status ".
- "WHERE ass_id = ".$ilDB->quote($this->getId(), "integer").
- " AND usr_id = ".$ilDB->quote($a_user_id, "integer").
- $and_grade;
-
- $set = $ilDB->query($q);
-
- while($rec = $ilDB->fetchAssoc($set))
- {
- $sub = new ilExSubmission($this, $a_user_id);
-
- $data["sent_time"] = $rec["sent_time"];
- $data["submission"] = $sub->getLastSubmission();
- $data["status_time"] = $rec["status_time"];
- $data["feedback_time"] = $rec["feedback_time"];
- $data["notice"] = $rec["notice"];
- $data["status"] = $rec["status"];
- $data["mark"] = $rec["mark"];
- $data["comment"] = $rec["u_comment"];
- }
-
- return $data;
-
- }
-
- /**
- * Create member status record for a new participant for all assignments
- */
- static function createNewUserRecords($a_user_id, $a_exc_id)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- $ass_data = self::getAssignmentDataOfExercise($a_exc_id);
- foreach ($ass_data as $ass)
- {
-//echo "-".$ass["id"]."-".$a_user_id."-";
- $ilDB->replace("exc_mem_ass_status", array(
- "ass_id" => array("integer", $ass["id"]),
- "usr_id" => array("integer", $a_user_id)
- ), array(
- "status" => array("text", "notgraded")
- ));
- }
- }
-
- /**
- * Create member status record for a new assignment for all participants
- */
- static function createNewAssignmentRecords($a_ass_id, $a_exc)
- {
- global $DIC;
-
- $ilDB = $DIC->database();
-
- include_once("./Modules/Exercise/classes/class.ilExerciseMembers.php");
- $exmem = new ilExerciseMembers($a_exc);
- $mems = $exmem->getMembers();
-
- foreach ($mems as $mem)
- {
- $ilDB->replace("exc_mem_ass_status", array(
- "ass_id" => array("integer", $a_ass_id),
- "usr_id" => array("integer", $mem)
- ), array(
- "status" => array("text", "notgraded")
- ));
- }
- }
-
- /**
- * Upload assignment files
- * (from creation form)
- */
- function uploadAssignmentFiles($a_files)
- {
- ilLoggerFactory::getLogger("exc")->debug("upload assignment files files = ",$a_files);
- include_once("./Modules/Exercise/classes/class.ilFSWebStorageExercise.php");
- $storage = new ilFSWebStorageExercise($this->getExerciseId(), $this->getId());
- $storage->create();
- $storage->uploadAssignmentFiles($a_files);
- }
-
-
- ////
- //// Multi-Feedback
- ////
-
- /**
- * Create member status record for a new assignment for all participants
- */
- function sendMultiFeedbackStructureFile(ilObjExercise $exercise)
- {
- global $DIC;
-
-
- // send and delete the zip file
- $deliverFilename = trim(str_replace(" ", "_", $this->getTitle()."_".$this->getId()));
- $deliverFilename = ilUtil::getASCIIFilename($deliverFilename);
- $deliverFilename = "multi_feedback_".$deliverFilename;
-
- $exc = new ilObjExercise($this->getExerciseId(), false);
-
- $cdir = getcwd();
-
- // create temporary directoy
- $tmpdir = ilUtil::ilTempnam();
- ilUtil::makeDir($tmpdir);
- $mfdir = $tmpdir."/".$deliverFilename;
- ilUtil::makeDir($mfdir);
-
- // create subfolders
" . $lng->txt("exc_total_members") . ": " . $this->getExerciseTotalMembers() . $add_info
+ );
+ $rd_creation_method->addOption($rd_creation_random);
+
+ $number_teams = new ilNumberInputGUI($lng->txt("exc_num_teams"), "number_teams");
+ $number_teams->setSize(3);
+ $number_teams->setMinValue(1);
+ $number_teams->setMaxValue($this->getExerciseTotalMembers());
+ $number_teams->setRequired(true);
+ $number_teams->setSuffix($lng->txt("exc_team_assignment_adopt_teams"));
+ $rd_creation_random->addSubItem($number_teams);
+
+ $min_team_participants = new ilNumberInputGUI($lng->txt("exc_min_team_participants"), "min_participants_team");
+ $min_team_participants->setSize(3);
+ $min_team_participants->setMinValue(1);
+ $min_team_participants->setMaxValue($this->getExerciseTotalMembers());
+ $min_team_participants->setRequired(true);
+ $min_team_participants->setSuffix($lng->txt("exc_participants"));
+ $rd_creation_random->addSubItem($min_team_participants);
+
+ $max_team_participants = new ilNumberInputGUI($lng->txt("exc_max_team_participants"), "max_participants_team");
+ $max_team_participants->setSize(3);
+ $max_team_participants->setMinValue(1);
+ $max_team_participants->setMaxValue($this->getExerciseTotalMembers());
+ $max_team_participants->setRequired(true);
+ $max_team_participants->setSuffix($lng->txt("exc_participants"));
+ $rd_creation_random->addSubItem($max_team_participants);
+
+ $options = ilExAssignmentTeam::getAdoptableTeamAssignments($this->exercise_id);
+ if (count($options)) {
+ $radio_assignment = new ilRadioOption(
+ $lng->txt("exc_team_by_assignment"),
+ ilExAssignment::TEAMS_FORMED_BY_ASSIGNMENT,
+ $lng->txt("exc_team_by_assignment_info")
+ );
+
+ $radio_assignment_adopt = new ilRadioGroupInputGUI($lng->txt("exc_assignment"), "ass_adpt");
+ $radio_assignment_adopt->setRequired(true);
+ $radio_assignment_adopt->addOption(new ilRadioOption($lng->txt("exc_team_assignment_adopt_none"), -1));
+
+ foreach ($options as $id => $item) {
+ $option = new ilRadioOption($item["title"], $id);
+ $option->setInfo($lng->txt("exc_team_assignment_adopt_teams") . ": " . $item["teams"]);
+ $radio_assignment_adopt->addOption($option);
+ }
+ $radio_assignment->addSubItem($radio_assignment_adopt);
+ $rd_creation_method->addOption($radio_assignment);
+ }
+
+ $radio_tutors->addSubItem($rd_creation_method);
+ }
+ $rd_team->addOption($radio_participants);
+ $rd_team->addOption($radio_tutors);
+ /*if(!$has_teams) {
+ $rd_team->addOption($radio_assignment);
+ }*/
+ $form->addItem($rd_team);
+
+ if ($has_teams) {
+ $rd_team->setDisabled(true);
+ }
+ }
+
+ // mandatory
+ $cb = new ilCheckboxInputGUI($lng->txt("exc_mandatory"), "mandatory");
+ $cb->setInfo($lng->txt("exc_mandatory_info"));
+ $cb->setChecked(true);
+ $form->addItem($cb);
+
+ // Work Instructions
+ $sub_header = new ilFormSectionHeaderGUI();
+ $sub_header->setTitle($lng->txt("exc_work_instructions"), "work_instructions");
+ $form->addItem($sub_header);
+
+ $desc_input = new ilTextAreaInputGUI($lng->txt("exc_instruction"), "instruction");
+ $desc_input->setRows(20);
+ $desc_input->setUseRte(true);
+ $desc_input->setRteTagSet("mini");
+ $form->addItem($desc_input);
+
+ // files
+ if ($a_mode == "create") {
+ $files = new ilFileWizardInputGUI($lng->txt('objs_file'), 'files');
+ $files->setFilenames(array(0 => ''));
+ $form->addItem($files);
+ }
+
+ // Schedule
+ $sub_header = new ilFormSectionHeaderGUI();
+ $sub_header->setTitle($lng->txt("exc_schedule"), "schedule");
+ $form->addItem($sub_header);
+
+ // start time
+ $start_date = new ilDateTimeInputGUI($lng->txt("exc_start_time"), "start_time");
+ $start_date->setShowTime(true);
+ $form->addItem($start_date);
+
+ // Deadline Mode
+ $radg = new ilRadioGroupInputGUI($lng->txt("exc_deadline"), "deadline_mode");
+ $radg->setValue(0);
+ $op1 = new ilRadioOption($lng->txt("exc_fixed_date"), 0, $lng->txt("exc_fixed_date_info"));
+ $radg->addOption($op1);
+ $op2 = new ilRadioOption($lng->txt("exc_relative_date"), 1, $lng->txt("exc_relative_date_info"));
+ $radg->addOption($op2);
+ $form->addItem($radg);
+
+ // Deadline fixed date
+ $deadline = new ilDateTimeInputGUI($lng->txt("date"), "deadline");
+ $deadline->setShowTime(true);
+ $op1->addSubItem($deadline);
+
+ // extended Deadline
+ $deadline2 = new ilDateTimeInputGUI($lng->txt("exc_deadline_extended"), "deadline2");
+ $deadline2->setInfo($lng->txt("exc_deadline_extended_info"));
+ $deadline2->setShowTime(true);
+ $deadline->addSubItem($deadline2);
+
+
+ // submit reminder
+ $rmd_submit = new ilCheckboxInputGUI($this->lng->txt("exc_reminder_submit_setting"), "rmd_submit_status");
+
+ $rmd_submit_start = new ilNumberInputGUI($this->lng->txt("exc_reminder_start"), "rmd_submit_start");
+ $rmd_submit_start->setSize(3);
+ $rmd_submit_start->setMaxLength(3);
+ $rmd_submit_start->setSuffix($lng->txt('days'));
+ $rmd_submit_start->setInfo($this->lng->txt("exc_reminder_start_info"));
+ $rmd_submit_start->setRequired(true);
+ $rmd_submit_start->setMinValue(1);
+ $rmd_submit->addSubItem($rmd_submit_start);
+
+ $rmd_submit_frequency = new ilNumberInputGUI($this->lng->txt("exc_reminder_frequency"), "rmd_submit_freq");
+ $rmd_submit_frequency->setSize(3);
+ $rmd_submit_frequency->setMaxLength(3);
+ $rmd_submit_frequency->setSuffix($lng->txt('days'));
+ $rmd_submit_frequency->setRequired(true);
+ $rmd_submit_frequency->setMinValue(1);
+ $rmd_submit->addSubItem($rmd_submit_frequency);
+
+ $rmd_submit_end = new ilDateTimeInputGUI($lng->txt("exc_reminder_end"), "rmd_submit_end");
+ $rmd_submit_end->setRequired(true);
+ $rmd_submit->addSubItem($rmd_submit_end);
+
+ $rmd_submit->addSubItem($this->addMailTemplatesRadio(ilExAssignmentReminder::SUBMIT_REMINDER));
+
+ // grade reminder
+ $rmd_grade = new ilCheckboxInputGUI($this->lng->txt("exc_reminder_grade_setting"), "rmd_grade_status");
+
+ $rmd_grade_frequency = new ilNumberInputGUI($this->lng->txt("exc_reminder_frequency"), "rmd_grade_freq");
+ $rmd_grade_frequency->setSize(3);
+ $rmd_grade_frequency->setMaxLength(3);
+ $rmd_grade_frequency->setSuffix($lng->txt('days'));
+ $rmd_grade_frequency->setRequired(true);
+ $rmd_grade_frequency->setMinValue(1);
+ $rmd_grade->addSubItem($rmd_grade_frequency);
+
+ $rmd_grade_end = new ilDateTimeInputGUI($lng->txt("exc_reminder_end"), "rmd_grade_end");
+ $rmd_grade_end->setRequired(true);
+ $rmd_grade->addSubItem($rmd_grade_end);
+
+ $rmd_grade->addSubItem($this->addMailTemplatesRadio(ilExAssignmentReminder::GRADE_REMINDER));
+
+ $form->addItem($rmd_submit);
+ $form->addItem($rmd_grade);
+
+ // relative deadline
+ $ti = new ilNumberInputGUI($lng->txt("days"), "relative_deadline");
+ $ti->setMaxLength(3);
+ $ti->setSize(3);
+ $op2->addSubItem($ti);
+
+
+ // max number of files
+ if ($ass_type->usesFileUpload()) {
+ $sub_header = new ilFormSectionHeaderGUI();
+ $sub_header->setTitle($ass_type->getTitle());
+ $form->addItem($sub_header);
+ $max_file_tgl = new ilCheckboxInputGUI($lng->txt("exc_max_file_tgl"), "max_file_tgl");
+ $form->addItem($max_file_tgl);
+
+ $max_file = new ilNumberInputGUI($lng->txt("exc_max_file"), "max_file");
+ $max_file->setInfo($lng->txt("exc_max_file_info"));
+ $max_file->setRequired(true);
+ $max_file->setSize(3);
+ $max_file->setMinValue(1);
+ $max_file_tgl->addSubItem($max_file);
+ }
+
+ // after submission
+ $sub_header = new ilFormSectionHeaderGUI();
+ $sub_header->setTitle($lng->txt("exc_after_submission"), "after_submission");
+ $form->addItem($sub_header);
+ if (!$ass_type->usesTeams()) {
+ // peer review
+ $peer = new ilCheckboxInputGUI($lng->txt("exc_peer_review"), "peer");
+ $peer->setInfo($lng->txt("exc_peer_review_ass_setting_info"));
+ $form->addItem($peer);
+ }
+
+
+ // global feedback
+
+ $fb = new ilCheckboxInputGUI($lng->txt("exc_global_feedback_file"), "fb");
+ $form->addItem($fb);
+
+ $fb_file = new ilFileInputGUI($lng->txt("file"), "fb_file");
+ $fb_file->setRequired(true); // will be disabled on update if file exists - see getAssignmentValues()
+ // $fb_file->setAllowDeletion(true); makes no sense if required (overwrite or keep)
+ $fb->addSubItem($fb_file);
+
+ $fb_date = new ilRadioGroupInputGUI($lng->txt("exc_global_feedback_file_date"), "fb_date");
+ $fb_date->setRequired(true);
+ $fb_date->addOption(new ilRadioOption($lng->txt("exc_global_feedback_file_date_deadline"), ilExAssignment::FEEDBACK_DATE_DEADLINE));
+ $fb_date->addOption(new ilRadioOption($lng->txt("exc_global_feedback_file_date_upload"), ilExAssignment::FEEDBACK_DATE_SUBMISSION));
+
+ //Extra radio option with date selection
+ $fb_date_custom_date = new ilDateTimeInputGUI($lng->txt("date"), "fb_date_custom");
+ $fb_date_custom_date->setRequired(true);
+ $fb_date_custom_date->setShowTime(true);
+ $fb_date_custom_option = new ilRadioOption($lng->txt("exc_global_feedback_file_after_date"), ilExAssignment::FEEDBACK_DATE_CUSTOM);
+ $fb_date_custom_option->addSubItem($fb_date_custom_date);
+ $fb_date->addOption($fb_date_custom_option);
+
+
+ $fb->addSubItem($fb_date);
+
+ $fb_cron = new ilCheckboxInputGUI($lng->txt("exc_global_feedback_file_cron"), "fb_cron");
+ $fb_cron->setInfo($lng->txt("exc_global_feedback_file_cron_info"));
+ $fb->addSubItem($fb_cron);
+
+
+ if ($a_mode == "create") {
+ $form->addCommandButton("saveAssignment", $lng->txt("save"));
+ $form->addCommandButton("listAssignments", $lng->txt("cancel"));
+ } else {
+ $form->addCommandButton("updateAssignment", $lng->txt("save"));
+ $form->addCommandButton("listAssignments", $lng->txt("cancel"));
+ }
+
+ return $form;
+ }
+
+ public function addMailTemplatesRadio($a_reminder_type)
+ {
+ global $DIC;
+
+ $post_var = "rmd_" . $a_reminder_type . "_template_id";
+
+ $r_group = new ilRadioGroupInputGUI($this->lng->txt("exc_reminder_mail_template"), $post_var);
+ $r_group->setRequired(true);
+ $r_group->addOption(new ilRadioOption($this->lng->txt("exc_reminder_mail_no_tpl"), 0));
+
+ switch ($a_reminder_type) {
+ case ilExAssignmentReminder::SUBMIT_REMINDER:
+ include_once "Modules/Exercise/classes/class.ilExcMailTemplateSubmitReminderContext.php";
+ $context = new ilExcMailTemplateSubmitReminderContext();
+ break;
+ case ilExAssignmentReminder::GRADE_REMINDER:
+ include_once "Modules/Exercise/classes/class.ilExcMailTemplateGradeReminderContext.php";
+ $context = new ilExcMailTemplateGradeReminderContext();
+ break;
+ case ilExAssignmentReminder::FEEDBACK_REMINDER:
+ include_once "Modules/Exercise/classes/class.ilExcMailTemplatePeerReminderContext.php";
+ $context = new ilExcMailTemplatePeerReminderContext();
+ break;
+ default:
+ exit();
+ }
+
+ /** @var \ilMailTemplateService $templateService */
+ $templateService = $DIC['mail.texttemplates.service'];
+ foreach ($templateService->loadTemplatesForContextId((string) $context->getId()) as $template) {
+ $r_group->addOption(new ilRadioOption($template->getTitle(), $template->getTplId()));
+ }
+
+ return $r_group;
+ }
+
+ /**
+ * Custom form validation
+ *
+ * @param ilPropertyFormGUI $a_form
+ * @return array
+ */
+ protected function processForm(ilPropertyFormGUI $a_form)
+ {
+ $lng = $this->lng;
+
+ $protected_peer_review_groups = false;
+
+ if ($this->assignment) {
+ if ($this->assignment->getPeerReview()) {
+ include_once "Modules/Exercise/classes/class.ilExPeerReview.php";
+ $peer_review = new ilExPeerReview($this->assignment);
+ if ($peer_review->hasPeerReviewGroups()) {
+ $protected_peer_review_groups = true;
+ }
+ }
+
+ if ($this->assignment->getFeedbackFile()) {
+ $a_form->getItemByPostVar("fb_file")->setRequired(false); // #15467
+ }
+ }
+
+ $valid = $a_form->checkInput();
+
+ if ($protected_peer_review_groups) {
+ // checkInput() will add alert to disabled fields
+ $a_form->getItemByPostVar("deadline")->setAlert(null);
+ $a_form->getItemByPostVar("deadline2")->setAlert(null);
+ }
+
+ if ($valid) {
+ $type = $a_form->getInput("type");
+ $ass_type = $this->types->getById($type);
+
+ // dates
+
+ $time_start = $a_form->getItemByPostVar("start_time")->getDate();
+ $time_start = $time_start
+ ? $time_start->get(IL_CAL_UNIX)
+ : null;
+
+ $time_deadline = $a_form->getItemByPostVar("deadline")->getDate();
+ $time_deadline = $time_deadline
+ ? $time_deadline->get(IL_CAL_UNIX)
+ : null;
+ $time_deadline_ext = $a_form->getItemByPostVar("deadline2")->getDate();
+ $time_deadline_ext = $time_deadline_ext
+ ? $time_deadline_ext->get(IL_CAL_UNIX)
+ : null;
+ $time_fb_custom_date = $a_form->getItemByPostVar("fb_date_custom")->getDate();
+ $time_fb_custom_date = $time_fb_custom_date
+ ? $time_fb_custom_date->get(IL_CAL_UNIX)
+ : null;
+
+ $reminder_submit_end_date = $a_form->getItemByPostVar("rmd_submit_end")->getDate();
+ $reminder_submit_end_date = $reminder_submit_end_date
+ ? $reminder_submit_end_date->get(IL_CAL_UNIX)
+ : null;
+
+ $reminder_grade_end_date = $a_form->getItemByPostVar("rmd_grade_end")->getDate();
+ $reminder_grade_end_date = $reminder_grade_end_date
+ ? $reminder_grade_end_date->get(IL_CAL_UNIX)
+ : null;
+
+ $time_deadline = null;
+ $time_deadline_ext = null;
+
+ if ((int) $a_form->getInput("deadline_mode") == ilExAssignment::DEADLINE_ABSOLUTE) {
+ $time_deadline = $a_form->getItemByPostVar("deadline")->getDate();
+ $time_deadline = $time_deadline
+ ? $time_deadline->get(IL_CAL_UNIX)
+ : null;
+ $time_deadline_ext = $a_form->getItemByPostVar("deadline2")->getDate();
+ $time_deadline_ext = $time_deadline_ext
+ ? $time_deadline_ext->get(IL_CAL_UNIX)
+ : null;
+ }
+
+
+ // handle disabled elements
+ if ($protected_peer_review_groups) {
+ $time_deadline = $this->assignment->getDeadline();
+ $time_deadline_ext = $this->assignment->getExtendedDeadline();
+ }
+
+ // no deadline?
+ if (!$time_deadline) {
+ // peer review
+ if (!$protected_peer_review_groups &&
+ $a_form->getInput("peer")) {
+ $a_form->getItemByPostVar("peer")
+ ->setAlert($lng->txt("exc_needs_fixed_deadline"));
+ $valid = false;
+ }
+ // global feedback
+ if ($a_form->getInput("fb") &&
+ $a_form->getInput("fb_date") == ilExAssignment::FEEDBACK_DATE_DEADLINE) {
+ $a_form->getItemByPostVar("fb")
+ ->setAlert($lng->txt("exc_needs_deadline"));
+ $valid = false;
+ }
+ } else {
+ // #18269
+ if ($a_form->getInput("peer")) {
+ $time_deadline_max = max($time_deadline, $time_deadline_ext);
+ $peer_dl = $this->assignment // #18380
+ ? $this->assignment->getPeerReviewDeadline()
+ : null;
+ if ($peer_dl && $peer_dl < $time_deadline_max) {
+ $a_form->getItemByPostVar($peer_dl < $time_deadline_ext
+ ? "deadline2"
+ : "deadline")
+ ->setAlert($lng->txt("exc_peer_deadline_mismatch"));
+ $valid = false;
+ }
+ }
+
+ if ($time_deadline_ext && $time_deadline_ext < $time_deadline) {
+ $a_form->getItemByPostVar("deadline2")
+ ->setAlert($lng->txt("exc_deadline_ext_mismatch"));
+ $valid = false;
+ }
+
+ $time_deadline_min = $time_deadline_ext
+ ? min($time_deadline, $time_deadline_ext)
+ : $time_deadline;
+ $time_deadline_max = max($time_deadline, $time_deadline_ext);
+
+ // start > any deadline ?
+ if ($time_start && $time_deadline_min && $time_start > $time_deadline_min) {
+ $a_form->getItemByPostVar("start_time")
+ ->setAlert($lng->txt("exc_start_date_should_be_before_end_date"));
+ $valid = false;
+ }
+ }
+
+ if ($ass_type->usesTeams()) {
+ if ($a_form->getInput("team_creation") == ilExAssignment::TEAMS_FORMED_BY_RANDOM &&
+ $a_form->getInput("team_creator") == ilExAssignment::TEAMS_FORMED_BY_TUTOR) {
+ $team_validation = $this->validationTeamsFormation(
+ $a_form->getInput("number_teams"),
+ $a_form->getInput("min_participants_team"),
+ $a_form->getInput("max_participants_team")
+ );
+ if ($team_validation['status'] == 'error') {
+ $a_form->getItemByPostVar("team_creation")
+ ->setAlert($team_validation['msg']);
+ $a_form->getItemByPostVar($team_validation["field"])
+ ->setAlert($lng->txt("exc_value_can_not_set"));
+ $valid = false;
+ }
+ }
+ }
+
+ if ($valid) {
+ $res = array(
+ // core
+ "type" => $a_form->getInput("type")
+ ,"title" => trim($a_form->getInput("title"))
+ ,"instruction" => trim($a_form->getInput("instruction"))
+ ,"mandatory" => $a_form->getInput("mandatory")
+ // dates
+ ,"start" => $time_start
+ ,"deadline" => $time_deadline
+ ,"deadline_ext" => $time_deadline_ext
+ ,"max_file" => $a_form->getInput("max_file_tgl")
+ ? $a_form->getInput("max_file")
+ : null
+ );
+
+ if ($a_form->getInput("team_creator") == ilExAssignment::TEAMS_FORMED_BY_TUTOR) {
+ $res['team_creator'] = $a_form->getInput("team_creator");
+ $res["team_creation"] = $a_form->getInput("team_creation");
+
+ if ($a_form->getInput("team_creation") == ilExAssignment::TEAMS_FORMED_BY_RANDOM) {
+ $res["number_teams"] = $a_form->getInput("number_teams");
+ $res["min_participants_team"] = $a_form->getInput("min_participants_team");
+ $res["max_participants_team"] = $a_form->getInput("max_participants_team");
+ } elseif ($a_form->getInput("team_creation") == ilExAssignment::TEAMS_FORMED_BY_ASSIGNMENT) {
+ $res['ass_adpt'] = $a_form->getInput("ass_adpt");
+ }
+ }
+
+ // portfolio template
+ //if($a_form->getInput("template_id") && $a_form->getInput("template"))
+ //{
+ // $res['template_id'] = $a_form->getInput("template_id");
+ //}
+
+ // text limitations
+ /*
+ if($a_form->getInput("limit_characters"))
+ {
+ $res['limit_characters'] = $a_form->getInput("limit_characters");
+ }
+ if($a_form->getInput("limit_characters") && $a_form->getInput("max_char_limit"))
+ {
+ $res['max_char_limit'] = $a_form->getInput("max_char_limit");
+ }
+ if($a_form->getInput("limit_characters") && $a_form->getInput("min_char_limit"))
+ {
+ $res['min_char_limit'] = $a_form->getInput("min_char_limit");
+
+ }*/
+
+
+ $res["deadline_mode"] = $a_form->getInput("deadline_mode");
+
+ if ($res["deadline_mode"] == ilExAssignment::DEADLINE_RELATIVE) {
+ $res["relative_deadline"] = $a_form->getInput("relative_deadline");
+ }
+
+ // peer
+ if ($a_form->getInput("peer") ||
+ $protected_peer_review_groups) {
+ $res["peer"] = true;
+ }
+
+ // files
+ if (is_array($_FILES["files"])) {
+ // #15994 - we are keeping the upload files array structure
+ // see ilFSStorageExercise::uploadAssignmentFiles()
+ $res["files"] = $_FILES["files"];
+ }
+
+ // global feedback
+ if ($a_form->getInput("fb")) {
+ $res["fb"] = true;
+ $res["fb_cron"] = $a_form->getInput("fb_cron");
+ $res["fb_date"] = $a_form->getInput("fb_date");
+ $res["fb_date_custom"] = $time_fb_custom_date;
+
+ if ($_FILES["fb_file"]["tmp_name"]) {
+ $res["fb_file"] = $_FILES["fb_file"];
+ }
+ }
+ if ($a_form->getInput("rmd_submit_status")) {
+ $res["rmd_submit_status"] = true;
+ $res["rmd_submit_start"] = $a_form->getInput("rmd_submit_start");
+ $res["rmd_submit_freq"] = $a_form->getInput("rmd_submit_freq");
+ $res["rmd_submit_end"] = $reminder_submit_end_date;
+ $res["rmd_submit_template_id"] = $a_form->getInput("rmd_submit_template_id");
+ }
+ if ($a_form->getInput("rmd_grade_status")) {
+ $res["rmd_grade_status"] = true;
+ $res["rmd_grade_freq"] = $a_form->getInput("rmd_grade_freq");
+ $res["rmd_grade_end"] = $reminder_grade_end_date;
+ $res["rmd_grade_template_id"] = $a_form->getInput("rmd_grade_template_id");
+ }
+
+ return $res;
+ } else {
+ ilUtil::sendFailure($lng->txt("form_input_not_valid"));
+ }
+ }
+ }
+
+ /**
+ * Import form values to assignment
+ *
+ * @param ilExAssignment $a_ass
+ * @param array $a_input
+ */
+ protected function importFormToAssignment(ilExAssignment $a_ass, array $a_input)
+ {
+ $is_create = !(bool) $a_ass->getId();
+
+ $a_ass->setTitle($a_input["title"]);
+ $a_ass->setInstruction($a_input["instruction"]);
+ $a_ass->setMandatory($a_input["mandatory"]);
+
+ $a_ass->setStartTime($a_input["start"]);
+ $a_ass->setDeadline($a_input["deadline"]);
+ $a_ass->setExtendedDeadline($a_input["deadline_ext"]);
+ $a_ass->setDeadlineMode($a_input["deadline_mode"]);
+ $a_ass->setRelativeDeadline($a_input["relative_deadline"]);
+
+ $a_ass->setMaxFile($a_input["max_file"]);
+ $a_ass->setTeamTutor($a_input["team_creator"]);
+
+ //$a_ass->setPortfolioTemplateId($a_input['template_id']);
+
+ //$a_ass->setMinCharLimit($a_input['min_char_limit']);
+ //$a_ass->setMaxCharLimit($a_input['max_char_limit']);
+
+ $a_ass->setPeerReview((bool) $a_input["peer"]);
+
+ // peer review default values (on separate form)
+ if ($is_create) {
+ $a_ass->setPeerReviewMin(2);
+ $a_ass->setPeerReviewSimpleUnlock(false);
+ $a_ass->setPeerReviewValid(ilExAssignment::PEER_REVIEW_VALID_NONE);
+ $a_ass->setPeerReviewPersonalized(false);
+ $a_ass->setPeerReviewFileUpload(false);
+ $a_ass->setPeerReviewText(true);
+ $a_ass->setPeerReviewRating(true);
+ }
+
+ if ($a_input["fb"]) {
+ $a_ass->setFeedbackCron($a_input["fb_cron"]); // #13380
+ $a_ass->setFeedbackDate($a_input["fb_date"]);
+ $a_ass->setFeedbackDateCustom($a_input["fb_date_custom"]);
+ }
+
+ // id needed for file handling
+ if ($is_create) {
+ $a_ass->save();
+
+ // #15994 - assignment files
+ if (is_array($a_input["files"])) {
+ $a_ass->uploadAssignmentFiles($a_input["files"]);
+ }
+ } else {
+ // remove global feedback file?
+ if (!$a_input["fb"]) {
+ $a_ass->deleteGlobalFeedbackFile();
+ $a_ass->setFeedbackFile(null);
+ }
+
+ $a_ass->update();
+ }
+
+ // add global feedback file?
+ if ($a_input["fb"]) {
+ if (is_array($a_input["fb_file"])) {
+ $a_ass->handleGlobalFeedbackFileUpload($a_input["fb_file"]);
+ $a_ass->update();
+ }
+ }
+ $this->importFormToAssignmentReminders($a_input, $a_ass->getId());
+ }
+
+ protected function importFormToAssignmentReminders($a_input, $a_ass_id)
+ {
+ $reminder = new ilExAssignmentReminder($this->exercise_id, $a_ass_id, ilExAssignmentReminder::SUBMIT_REMINDER);
+ $this->saveReminderData($reminder, $a_input);
+
+ $reminder = new ilExAssignmentReminder($this->exercise_id, $a_ass_id, ilExAssignmentReminder::GRADE_REMINDER);
+ $this->saveReminderData($reminder, $a_input);
+ }
+
+ //todo maybe we can refactor this method to use only one importFormToReminders
+ protected function importPeerReviewFormToAssignmentReminders($a_input, $a_ass_id)
+ {
+ $reminder = new ilExAssignmentReminder($this->exercise_id, $a_ass_id, ilExAssignmentReminder::FEEDBACK_REMINDER);
+ $this->saveReminderData($reminder, $a_input);
+ }
+
+ protected function saveReminderData(ilExAssignmentReminder $reminder, $a_input)
+ {
+ if ($reminder->getReminderStatus() == null) {
+ $action = "save";
+ } else {
+ $action = "update";
+ }
+ $type = $reminder->getReminderType();
+ $reminder->setReminderStatus((bool) $a_input["rmd_" . $type . "_status"]);
+ $reminder->setReminderStart((int) $a_input["rmd_" . $type . "_start"]);
+ $reminder->setReminderEnd((int) $a_input["rmd_" . $type . "_end"]);
+ $reminder->setReminderFrequency((int) $a_input["rmd_" . $type . "_freq"]);
+ $reminder->setReminderMailTemplate((int) $a_input["rmd_" . $type . "_template_id"]);
+ $reminder->{$action}();
+ }
+
+ /**
+ * Save assignment
+ *
+ */
+ public function saveAssignmentObject()
+ {
+ $tpl = $this->tpl;
+ $lng = $this->lng;
+ $ilCtrl = $this->ctrl;
+
+ // #16163 - ignore ass id from request
+ $this->assignment = null;
+
+ $form = $this->initAssignmentForm((int) $_POST["type"], "create");
+ $input = $this->processForm($form);
+ if (is_array($input)) {
+ $ass = new ilExAssignment();
+ $ass->setExerciseId($this->exercise_id);
+ $ass->setType($input["type"]);
+ $ass_type = $ass->getAssignmentType();
+ $ass_type_gui = $this->type_guis->getById($ass->getType());
+
+ $this->importFormToAssignment($ass, $input);
+
+ $this->generateTeams($ass, $input);
+ ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true);
+
+ $ass_type_gui->importFormToAssignment($ass, $form);
+ $ass->update();
+
+ ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true);
+
+ // because of sub-tabs we stay on settings screen
+ $ilCtrl->setParameter($this, "ass_id", $ass->getId());
+ $ilCtrl->redirect($this, "editAssignment");
+ } else {
+ $form->setValuesByPost();
+ $tpl->setContent($form->getHtml());
+ }
+ }
+
+ /**
+ * Edit assignment
+ */
+ public function editAssignmentObject()
+ {
+ $ilTabs = $this->tabs;
+ $tpl = $this->tpl;
+
+ $this->setAssignmentHeader();
+ $ilTabs->activateTab("ass_settings");
+
+ $form = $this->initAssignmentForm($this->assignment->getType(), "edit");
+ $this->getAssignmentValues($form);
+ $tpl->setContent($form->getHTML());
+ }
+
+ /**
+ * Get current values for assignment from
+ */
+ public function getAssignmentValues(ilPropertyFormGUI $a_form)
+ {
+ $lng = $this->lng;
+ $ilCtrl = $this->ctrl;
+
+ $ass_type_gui = $this->type_guis->getById($this->assignment->getType());
+
+ $values = array();
+ $values["type"] = $this->assignment->getType();
+ $values["title"] = $this->assignment->getTitle();
+ $values["mandatory"] = $this->assignment->getMandatory();
+ $values["instruction"] = $this->assignment->getInstruction();
+ //$values['template_id'] = $this->assignment->getPortfolioTemplateId();
+
+ //if($this->assignment->getPortfolioTemplateId())
+ //{
+ // $values["template"] = 1;
+ //}
+
+ /*if($this->assignment->getMinCharLimit())
+ {
+ $values['limit_characters'] = 1;
+ $values['min_char_limit'] = $this->assignment->getMinCharLimit();
+ }
+ if($this->assignment->getMaxCharLimit())
+ {
+ $values['limit_characters'] = 1;
+ $values['max_char_limit'] = $this->assignment->getMaxCharLimit();
+ }*/
+
+ if ($this->assignment->getStartTime()) {
+ $values["start_time"] = new ilDateTime($this->assignment->getStartTime(), IL_CAL_UNIX);
+ }
+
+ if ($this->assignment->getAssignmentType()->usesFileUpload()) {
+ if ($this->assignment->getMaxFile()) {
+ $values["max_file_tgl"] = true;
+ $values["max_file"] = $this->assignment->getMaxFile();
+ }
+ }
+
+ if ($this->assignment->getAssignmentType()->usesTeams()) {
+ $values["team_creator"] = $this->assignment->getTeamTutor();
+ }
+
+ if ($this->assignment->getFeedbackDateCustom()) {
+ $values["fb_date_custom"] = new ilDateTime($this->assignment->getFeedbackDateCustom(), IL_CAL_UNIX);
+ }
+
+ //Reminders
+ $rmd_sub = new ilExAssignmentReminder($this->exercise_id, $this->assignment->getId(), ilExAssignmentReminder::SUBMIT_REMINDER);
+ if ($rmd_sub->getReminderStatus()) {
+ $values["rmd_submit_status"] = $rmd_sub->getReminderStatus();
+ $values["rmd_submit_start"] = $rmd_sub->getReminderStart();
+ $values["rmd_submit_end"] = new ilDateTime($rmd_sub->getReminderEnd(), IL_CAL_UNIX);
+ $values["rmd_submit_freq"] = $rmd_sub->getReminderFrequency();
+ $values["rmd_submit_template_id"] = $rmd_sub->getReminderMailTemplate();
+ }
+
+ $rmd_grade = new ilExAssignmentReminder($this->exercise_id, $this->assignment->getId(), ilExAssignmentReminder::GRADE_REMINDER);
+ if ($rmd_grade->getReminderStatus()) {
+ $values["rmd_grade_status"] = $rmd_grade->getReminderStatus();
+ $values["rmd_grade_end"] = new ilDateTime($rmd_grade->getReminderEnd(), IL_CAL_UNIX);
+ $values["rmd_grade_freq"] = $rmd_grade->getReminderFrequency();
+ $values["rmd_grade_template_id"] = $rmd_grade->getReminderMailTemplate();
+ }
+
+ $type_values = $ass_type_gui->getFormValuesArray($this->assignment);
+ $values = array_merge($values, $type_values);
+
+
+ $values["deadline_mode"] = $this->assignment->getDeadlineMode();
+ $values["relative_deadline"] = $this->assignment->getRelativeDeadline();
+
+ $a_form->setValuesByArray($values);
+
+ // global feedback
+ if ($this->assignment->getFeedbackFile()) {
+ $a_form->getItemByPostVar("fb")->setChecked(true);
+ $a_form->getItemByPostVar("fb_file")->setValue(basename($this->assignment->getGlobalFeedbackFilePath()));
+ $a_form->getItemByPostVar("fb_file")->setRequired(false); // #15467
+ $a_form->getItemByPostVar("fb_file")->setInfo(
+ // #16400
+ '' .
+ $lng->txt("download") . ''
+ );
+ }
+ $a_form->getItemByPostVar("fb_cron")->setChecked($this->assignment->hasFeedbackCron());
+ $a_form->getItemByPostVar("fb_date")->setValue($this->assignment->getFeedbackDate());
+
+ $this->handleDisabledFields($a_form, true);
+ }
+
+ protected function setDisabledFieldValues(ilPropertyFormGUI $a_form)
+ {
+ // dates
+ if ($this->assignment->getDeadline() > 0) {
+ $edit_date = new ilDateTime($this->assignment->getDeadline(), IL_CAL_UNIX);
+ $ed_item = $a_form->getItemByPostVar("deadline");
+ $ed_item->setDate($edit_date);
+
+ if ($this->assignment->getExtendedDeadline() > 0) {
+ $edit_date = new ilDateTime($this->assignment->getExtendedDeadline(), IL_CAL_UNIX);
+ $ed_item = $a_form->getItemByPostVar("deadline2");
+ $ed_item->setDate($edit_date);
+ }
+ }
+
+ if ($this->assignment->getPeerReview()) {
+ $a_form->getItemByPostVar("peer")->setChecked($this->assignment->getPeerReview());
+ }
+ }
+
+ protected function handleDisabledFields(ilPropertyFormGUI $a_form, $a_force_set_values = false)
+ {
+ // potentially disabled elements are initialized here to re-use this
+ // method after setValuesByPost() - see updateAssignmentObject()
+
+ // team assignments do not support peer review
+ // with no active peer review there is nothing to protect
+ if (!$this->assignment->getAssignmentType()->usesTeams() &&
+ $this->assignment->getPeerReview()) {
+ // #14450
+ include_once "Modules/Exercise/classes/class.ilExPeerReview.php";
+ $peer_review = new ilExPeerReview($this->assignment);
+ if ($peer_review->hasPeerReviewGroups()) {
+ // deadline(s) are past and must not change
+ $a_form->getItemByPostVar("deadline")->setDisabled(true);
+ $a_form->getItemByPostVar("deadline2")->setDisabled(true);
+
+ $a_form->getItemByPostVar("peer")->setDisabled(true);
+
+ $a_form->getItemByPostVar("deadline_mode")->setDisabled(true);
+ }
+ }
+
+ if ($a_force_set_values ||
+ ($peer_review && $peer_review->hasPeerReviewGroups())) {
+ $this->setDisabledFieldValues($a_form);
+ }
+ }
+
+ /**
+ * Update assignment
+ *
+ */
+ public function updateAssignmentObject()
+ {
+ $tpl = $this->tpl;
+ $lng = $this->lng;
+ $ilCtrl = $this->ctrl;
+ $ilTabs = $this->tabs;
+
+ $form = $this->initAssignmentForm($this->assignment->getType(), "edit");
+ $input = $this->processForm($form);
+
+ $ass_type = $this->assignment->getType();
+ $ass_type_gui = $this->type_guis->getById($ass_type);
+
+ if (is_array($input)) {
+ $old_deadline = $this->assignment->getDeadline();
+ $old_ext_deadline = $this->assignment->getExtendedDeadline();
+
+ $this->importFormToAssignment($this->assignment, $input);
+ $this->generateTeams($this->assignment, $input);
+
+ $ass_type_gui->importFormToAssignment($this->assignment, $form);
+ $this->assignment->update();
+
+ $new_deadline = $this->assignment->getDeadline();
+ $new_ext_deadline = $this->assignment->getExtendedDeadline();
+
+ // if deadlines were changed
+ if ($old_deadline != $new_deadline ||
+ $old_ext_deadline != $new_ext_deadline) {
+ $this->assignment->recalculateLateSubmissions();
+ }
+
+ ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true);
+ $ilCtrl->redirect($this, "editAssignment");
+ } else {
+ $this->setAssignmentHeader();
+ $ilTabs->activateTab("ass_settings");
+
+ $form->setValuesByPost();
+ $this->handleDisabledFields($form);
+ $tpl->setContent($form->getHtml());
+ }
+ }
+
+ /**
+ * Confirm assignments deletion
+ */
+ public function confirmAssignmentsDeletionObject()
+ {
+ $ilCtrl = $this->ctrl;
+ $tpl = $this->tpl;
+ $lng = $this->lng;
+
+ if (!is_array($_POST["id"]) || count($_POST["id"]) == 0) {
+ ilUtil::sendFailure($lng->txt("no_checkbox"), true);
+ $ilCtrl->redirect($this, "listAssignments");
+ } else {
+ include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php");
+ $cgui = new ilConfirmationGUI();
+ $cgui->setFormAction($ilCtrl->getFormAction($this));
+ $cgui->setHeaderText($lng->txt("exc_conf_del_assignments"));
+ $cgui->setCancel($lng->txt("cancel"), "listAssignments");
+ $cgui->setConfirm($lng->txt("delete"), "deleteAssignments");
+
+ foreach ($_POST["id"] as $i) {
+ $cgui->addItem("id[]", $i, ilExAssignment::lookupTitle($i));
+ }
+
+ $tpl->setContent($cgui->getHTML());
+ }
+ }
+
+ /**
+ * Delete assignments
+ */
+ public function deleteAssignmentsObject()
+ {
+ $ilCtrl = $this->ctrl;
+ $lng = $this->lng;
+
+ $delete = false;
+ if (is_array($_POST["id"])) {
+ foreach ($_POST["id"] as $id) {
+ $ass = new ilExAssignment(ilUtil::stripSlashes($id));
+ $ass->delete();
+ $delete = true;
+ }
+ }
+
+ if ($delete) {
+ ilUtil::sendSuccess($lng->txt("exc_assignments_deleted"), true);
+ }
+ $ilCtrl->setParameter($this, "ass_id", "");
+ $ilCtrl->redirect($this, "listAssignments");
+ }
+
+ /**
+ * Save assignments order
+ */
+ public function saveAssignmentOrderObject()
+ {
+ $lng = $this->lng;
+ $ilCtrl = $this->ctrl;
+
+ ilExAssignment::saveAssOrderOfExercise($this->exercise_id, $_POST["order"]);
+
+ ilUtil::sendSuccess($lng->txt("exc_saved_order"), true);
+ $ilCtrl->redirect($this, "listAssignments");
+ }
+
+ /**
+ * Order by deadline
+ */
+ public function orderAssignmentsByDeadlineObject()
+ {
+ $lng = $this->lng;
+ $ilCtrl = $this->ctrl;
+
+ ilExAssignment::orderAssByDeadline($this->exercise_id);
+
+ ilUtil::sendSuccess($lng->txt("exc_saved_order"), true);
+ $ilCtrl->redirect($this, "listAssignments");
+ }
+
+ /**
+ * Set assignment header
+ */
+ public function setAssignmentHeader()
+ {
+ $ilTabs = $this->tabs;
+ $lng = $this->lng;
+ $ilCtrl = $this->ctrl;
+ $tpl = $this->tpl;
+ $ilHelp = $this->help;
+
+ $tpl->setTitle($this->assignment->getTitle());
+ $tpl->setDescription("");
+
+ $ilTabs->clearTargets();
+ $ilHelp->setScreenIdComponent("exc");
+
+ $ilTabs->setBackTarget(
+ $lng->txt("back"),
+ $ilCtrl->getLinkTarget($this, "listAssignments")
+ );
+
+ $ilTabs->addTab(
+ "ass_settings",
+ $lng->txt("settings"),
+ $ilCtrl->getLinkTarget($this, "editAssignment")
+ );
+
+ if (!$this->assignment->getAssignmentType()->usesTeams() &&
+ $this->assignment->getPeerReview()) {
+ $ilTabs->addTab(
+ "peer_settings",
+ $lng->txt("exc_peer_review"),
+ $ilCtrl->getLinkTarget($this, "editPeerReview")
+ );
+ }
+
+ $ilTabs->addTab(
+ "ass_files",
+ $lng->txt("exc_instruction_files"),
+ $ilCtrl->getLinkTargetByClass(array("ilexassignmenteditorgui", "ilexassignmentfilesystemgui"), "listFiles")
+ );
+ }
+
+ public function downloadGlobalFeedbackFileObject()
+ {
+ $ilCtrl = $this->ctrl;
+
+ if (!$this->assignment ||
+ !$this->assignment->getFeedbackFile()) {
+ $ilCtrl->redirect($this, "returnToParent");
+ }
+
+ ilUtil::deliverFile($this->assignment->getGlobalFeedbackFilePath(), $this->assignment->getFeedbackFile());
+ }
+
+
+ //
+ // PEER REVIEW
+ //
+
+ protected function initPeerReviewForm()
+ {
+ $ilCtrl = $this->ctrl;
+ $lng = $this->lng;
+
+ include_once("./Services/Form/classes/class.ilPropertyFormGUI.php");
+ $form = new ilPropertyFormGUI();
+ $form->setTitle($lng->txt("exc_peer_review"));
+ $form->setFormAction($ilCtrl->getFormAction($this));
+
+ $peer_min = new ilNumberInputGUI($lng->txt("exc_peer_review_min_number"), "peer_min");
+ $peer_min->setInfo($lng->txt("exc_peer_review_min_number_info")); // #16161
+ $peer_min->setRequired(true);
+ $peer_min->setSize(3);
+ $peer_min->setValue(2);
+ $form->addItem($peer_min);
+
+ $peer_unlock = new ilRadioGroupInputGUI($lng->txt("exc_peer_review_simple_unlock"), "peer_unlock");
+ $peer_unlock->addOption(new ilRadioOption($lng->txt("exc_peer_review_simple_unlock_active"), 1));
+ $peer_unlock->addOption(new ilRadioOption($lng->txt("exc_peer_review_simple_unlock_inactive"), 0));
+ $peer_unlock->setRequired(true);
+ $peer_unlock->setValue(0);
+ $form->addItem($peer_unlock);
+
+ if ($this->enable_peer_review_completion) {
+ $peer_cmpl = new ilRadioGroupInputGUI($lng->txt("exc_peer_review_completion"), "peer_valid");
+ $option = new ilRadioOption($lng->txt("exc_peer_review_completion_none"), ilExAssignment::PEER_REVIEW_VALID_NONE);
+ $option->setInfo($lng->txt("exc_peer_review_completion_none_info"));
+ $peer_cmpl->addOption($option);
+ $option = new ilRadioOption($lng->txt("exc_peer_review_completion_one"), ilExAssignment::PEER_REVIEW_VALID_ONE);
+ $option->setInfo($lng->txt("exc_peer_review_completion_one_info"));
+ $peer_cmpl->addOption($option);
+ $option = new ilRadioOption($lng->txt("exc_peer_review_completion_all"), ilExAssignment::PEER_REVIEW_VALID_ALL);
+ $option->setInfo($lng->txt("exc_peer_review_completion_all_info"));
+ $peer_cmpl->addOption($option);
+ $peer_cmpl->setRequired(true);
+ $peer_cmpl->setValue(ilExAssignment::PEER_REVIEW_VALID_NONE);
+ $form->addItem($peer_cmpl);
+ }
+
+ $peer_dl = new ilDateTimeInputGUI($lng->txt("exc_peer_review_deadline"), "peer_dl");
+ $peer_dl->setInfo($lng->txt("exc_peer_review_deadline_info"));
+ $peer_dl->setShowTime(true);
+ $form->addItem($peer_dl);
+
+ $peer_prsl = new ilCheckboxInputGUI($lng->txt("exc_peer_review_personal"), "peer_prsl");
+ $peer_prsl->setInfo($lng->txt("exc_peer_review_personal_info"));
+ $form->addItem($peer_prsl);
+
+ //feedback reminders
+ $rmd_feedback = new ilCheckboxInputGUI($this->lng->txt("exc_reminder_feedback_setting"), "rmd_peer_status");
+
+ $rmd_submit_start = new ilNumberInputGUI($this->lng->txt("exc_reminder_feedback_start"), "rmd_peer_start");
+ $rmd_submit_start->setSize(3);
+ $rmd_submit_start->setMaxLength(3);
+ $rmd_submit_start->setSuffix($lng->txt('days'));
+ $rmd_submit_start->setRequired(true);
+ $rmd_submit_start->setMinValue(1);
+ $rmd_feedback->addSubItem($rmd_submit_start);
+
+ $rmd_submit_frequency = new ilNumberInputGUI($this->lng->txt("exc_reminder_frequency"), "rmd_peer_freq");
+ $rmd_submit_frequency->setSize(3);
+ $rmd_submit_frequency->setMaxLength(3);
+ $rmd_submit_frequency->setSuffix($lng->txt('days'));
+ $rmd_submit_frequency->setRequired(true);
+ $rmd_submit_frequency->setMinValue(1);
+ $rmd_feedback->addSubItem($rmd_submit_frequency);
+
+ $rmd_submit_end = new ilDateTimeInputGUI($lng->txt("exc_reminder_end"), "rmd_peer_end");
+ $rmd_submit_end->setRequired(true);
+ $rmd_feedback->addSubItem($rmd_submit_end);
+
+ $rmd_feedback->addSubItem($this->addMailTemplatesRadio(ilExAssignmentReminder::FEEDBACK_REMINDER));
+
+ $form->addItem($rmd_feedback);
+
+ // criteria
+
+ $cats = new ilRadioGroupInputGUI($lng->txt("exc_criteria_catalogues"), "crit_cat");
+ $form->addItem($cats);
+
+ // default (no catalogue)
+
+ $def = new ilRadioOption($lng->txt("exc_criteria_catalogue_default"), -1);
+ $cats->addOption($def);
+
+ $peer_text = new ilCheckboxInputGUI($lng->txt("exc_peer_review_text"), "peer_text");
+ $def->addSubItem($peer_text);
+
+ $peer_char = new ilNumberInputGUI($lng->txt("exc_peer_review_min_chars"), "peer_char");
+ $peer_char->setInfo($lng->txt("exc_peer_review_min_chars_info"));
+ $peer_char->setSize(3);
+ $peer_text->addSubItem($peer_char);
+
+ $peer_rating = new ilCheckboxInputGUI($lng->txt("exc_peer_review_rating"), "peer_rating");
+ $def->addSubItem($peer_rating);
+
+ $peer_file = new ilCheckboxInputGUI($lng->txt("exc_peer_review_file"), "peer_file");
+ $peer_file->setInfo($lng->txt("exc_peer_review_file_info"));
+ $def->addSubItem($peer_file);
+
+ // catalogues
+
+ include_once "Modules/Exercise/classes/class.ilExcCriteriaCatalogue.php";
+ $cat_objs = ilExcCriteriaCatalogue::getInstancesByParentId($this->exercise_id);
+ if (sizeof($cat_objs)) {
+ include_once "Modules/Exercise/classes/class.ilExcCriteria.php";
+ foreach ($cat_objs as $cat_obj) {
+ $crits = ilExcCriteria::getInstancesByParentId($cat_obj->getId());
+
+ // only non-empty catalogues
+ if (sizeof($crits)) {
+ $titles = array();
+ foreach ($crits as $crit) {
+ $titles[] = $crit->getTitle();
+ }
+ $opt = new ilRadioOption($cat_obj->getTitle(), $cat_obj->getId());
+ $opt->setInfo(implode(", ", $titles));
+ $cats->addOption($opt);
+ }
+ }
+ } else {
+ // see ilExcCriteriaCatalogueGUI::view()
+ $url = $ilCtrl->getLinkTargetByClass("ilexccriteriacataloguegui", "");
+ $def->setInfo('[+] ' .
+ $lng->txt("exc_add_criteria_catalogue") .
+ '');
+ }
+
+
+ $form->addCommandButton("updatePeerReview", $lng->txt("save"));
+ $form->addCommandButton("editAssignment", $lng->txt("cancel"));
+
+ return $form;
+ }
+
+ public function editPeerReviewObject(ilPropertyFormGUI $a_form = null)
+ {
+ $tpl = $this->tpl;
+ $ilTabs = $this->tabs;
+ $tpl = $this->tpl;
+
+ $this->setAssignmentHeader();
+ $ilTabs->activateTab("peer_settings");
+
+ if ($a_form === null) {
+ $a_form = $this->initPeerReviewForm();
+ $this->getPeerReviewValues($a_form);
+ }
+ $tpl->setContent($a_form->getHTML());
+ }
+
+ protected function getPeerReviewValues($a_form)
+ {
+ $values = array();
+
+ if ($this->assignment->getPeerReviewDeadline() > 0) {
+ $values["peer_dl"] = new ilDateTime($this->assignment->getPeerReviewDeadline(), IL_CAL_UNIX);
+ }
+
+ $this->assignment->getId();
+ $this->exercise_id;
+ $reminder = new ilExAssignmentReminder($this->exercise_id, $this->assignment->getId(), ilExAssignmentReminder::FEEDBACK_REMINDER);
+ if ($reminder->getReminderStatus()) {
+ $values["rmd_peer_status"] = $reminder->getReminderStatus();
+ $values["rmd_peer_start"] = $reminder->getReminderStart();
+ $values["rmd_peer_end"] = new ilDateTime($reminder->getReminderEnd(), IL_CAL_UNIX);
+ $values["rmd_peer_freq"] = $reminder->getReminderFrequency();
+ $values["rmd_peer_template_id"] = $reminder->getReminderMailTemplate();
+ }
+
+ $a_form->setValuesByArray($values);
+
+ $this->handleDisabledPeerFields($a_form, true);
+ }
+
+ protected function setDisabledPeerReviewFieldValues(ilPropertyFormGUI $a_form)
+ {
+ $a_form->getItemByPostVar("peer_min")->setValue($this->assignment->getPeerReviewMin());
+ $a_form->getItemByPostVar("peer_prsl")->setChecked($this->assignment->hasPeerReviewPersonalized());
+ $a_form->getItemByPostVar("peer_unlock")->setValue((int) $this->assignment->getPeerReviewSimpleUnlock());
+
+ if ($this->enable_peer_review_completion) {
+ $a_form->getItemByPostVar("peer_valid")->setValue($this->assignment->getPeerReviewValid());
+ }
+
+ $cat = $this->assignment->getPeerReviewCriteriaCatalogue();
+ if ($cat < 1) {
+ $cat = -1;
+
+ // default / no catalogue
+ $a_form->getItemByPostVar("peer_text")->setChecked($this->assignment->hasPeerReviewText());
+ $a_form->getItemByPostVar("peer_rating")->setChecked($this->assignment->hasPeerReviewRating());
+ $a_form->getItemByPostVar("peer_file")->setChecked($this->assignment->hasPeerReviewFileUpload());
+ if ($this->assignment->getPeerReviewChars() > 0) {
+ $a_form->getItemByPostVar("peer_char")->setValue($this->assignment->getPeerReviewChars());
+ }
+ }
+ $a_form->getItemByPostVar("crit_cat")->setValue($cat);
+ }
+
+ protected function handleDisabledPeerFields(ilPropertyFormGUI $a_form, $a_force_set_values = false)
+ {
+ // #14450
+ include_once "Modules/Exercise/classes/class.ilExPeerReview.php";
+ $peer_review = new ilExPeerReview($this->assignment);
+ if ($peer_review->hasPeerReviewGroups()) {
+ // JourFixe, 2015-05-11 - editable again
+ // $a_form->getItemByPostVar("peer_dl")->setDisabled(true);
+
+ $a_form->getItemByPostVar("peer_min")->setDisabled(true);
+ $a_form->getItemByPostVar("peer_prsl")->setDisabled(true);
+ $a_form->getItemByPostVar("peer_unlock")->setDisabled(true);
+
+ if ($this->enable_peer_review_completion) {
+ $a_form->getItemByPostVar("peer_valid")->setDisabled(true);
+ }
+
+ $a_form->getItemByPostVar("crit_cat")->setDisabled(true);
+ $a_form->getItemByPostVar("peer_text")->setDisabled(true);
+ $a_form->getItemByPostVar("peer_char")->setDisabled(true);
+ $a_form->getItemByPostVar("peer_rating")->setDisabled(true);
+ $a_form->getItemByPostVar("peer_file")->setDisabled(true);
+
+ // required number input is a problem
+ $min = new ilHiddenInputGUI("peer_min");
+ $min->setValue($this->assignment->getPeerReviewMin());
+ $a_form->addItem($min);
+ }
+
+ if ($a_force_set_values ||
+ $peer_review->hasPeerReviewGroups()) {
+ $this->setDisabledPeerReviewFieldValues($a_form);
+ }
+ }
+
+ protected function processPeerReviewForm(ilPropertyFormGUI $a_form)
+ {
+ $lng = $this->lng;
+
+ $protected_peer_review_groups = false;
+ include_once "Modules/Exercise/classes/class.ilExPeerReview.php";
+ $peer_review = new ilExPeerReview($this->assignment);
+ if ($peer_review->hasPeerReviewGroups()) {
+ $protected_peer_review_groups = true;
+ }
+
+ $valid = $a_form->checkInput();
+ if ($valid) {
+ // dates
+ $time_deadline = $this->assignment->getDeadline();
+ $time_deadline_ext = $this->assignment->getExtendedDeadline();
+ $time_deadline_max = max($time_deadline, $time_deadline_ext);
+
+ $date = $a_form->getItemByPostVar("peer_dl")->getDate();
+ $time_peer = $date
+ ? $date->get(IL_CAL_UNIX)
+ : null;
+
+ $reminder_date = $a_form->getItemByPostVar("rmd_peer_end")->getDate();
+ $reminder_date = $reminder_date
+ ? $reminder_date->get(IL_CAL_UNIX)
+ : null;
+
+ // peer < any deadline?
+ if ($time_peer && $time_deadline_max && $time_peer < $time_deadline_max) {
+ $a_form->getItemByPostVar("peer_dl")
+ ->setAlert($lng->txt("exc_peer_deadline_mismatch"));
+ $valid = false;
+ }
+
+ if (!$protected_peer_review_groups) {
+ if ($a_form->getInput("crit_cat") < 0 &&
+ !$a_form->getInput("peer_text") &&
+ !$a_form->getInput("peer_rating") &&
+ !$a_form->getInput("peer_file")) {
+ $a_form->getItemByPostVar("peer_file")
+ ->setAlert($lng->txt("select_one"));
+ $valid = false;
+ }
+ }
+
+ if ($valid) {
+ $res = array();
+ $res["peer_dl"] = $time_peer;
+
+ if ($protected_peer_review_groups) {
+ $res["peer_min"] = $this->assignment->getPeerReviewMin();
+ $res["peer_unlock"] = $this->assignment->getPeerReviewSimpleUnlock();
+ $res["peer_prsl"] = $this->assignment->hasPeerReviewPersonalized();
+ $res["peer_valid"] = $this->assignment->getPeerReviewValid();
+
+ $res["peer_text"] = $this->assignment->hasPeerReviewText();
+ $res["peer_rating"] = $this->assignment->hasPeerReviewRating();
+ $res["peer_file"] = $this->assignment->hasPeerReviewFileUpload();
+ $res["peer_char"] = $this->assignment->getPeerReviewChars();
+ $res["crit_cat"] = $this->assignment->getPeerReviewCriteriaCatalogue();
+
+ $res["peer_valid"] = $this->enable_peer_review_completion
+ ? $res["peer_valid"]
+ : null;
+ } else {
+ $res["peer_min"] = $a_form->getInput("peer_min");
+ $res["peer_unlock"] = $a_form->getInput("peer_unlock");
+ $res["peer_prsl"] = $a_form->getInput("peer_prsl");
+ $res["peer_valid"] = $a_form->getInput("peer_valid");
+
+ $res["peer_text"] = $a_form->getInput("peer_text");
+ $res["peer_rating"] = $a_form->getInput("peer_rating");
+ $res["peer_file"] = $a_form->getInput("peer_file");
+ $res["peer_char"] = $a_form->getInput("peer_char");
+ $res["crit_cat"] = $a_form->getInput("crit_cat");
+ }
+ if ($a_form->getInput("rmd_peer_status")) {
+ $res["rmd_peer_status"] = $a_form->getInput("rmd_peer_status");
+ $res["rmd_peer_start"] = $a_form->getInput("rmd_peer_start");
+ $res["rmd_peer_end"] = $reminder_date;
+ $res["rmd_peer_freq"] = $a_form->getInput("rmd_peer_freq");
+ $res["rmd_peer_template_id"] = $a_form->getInput("rmd_peer_template_id");
+ }
+
+ return $res;
+ } else {
+ ilUtil::sendFailure($lng->txt("form_input_not_valid"));
+ }
+ }
+ }
+
+ protected function importPeerReviewFormToAssignment(ilExAssignment $a_ass, array $a_input)
+ {
+ $a_ass->setPeerReviewMin($a_input["peer_min"]);
+ $a_ass->setPeerReviewDeadline($a_input["peer_dl"]);
+ $a_ass->setPeerReviewSimpleUnlock($a_input["peer_unlock"]);
+ $a_ass->setPeerReviewPersonalized($a_input["peer_prsl"]);
+
+ // #18964
+ $a_ass->setPeerReviewValid($a_input["peer_valid"]
+ ? $a_input["peer_valid"]
+ : ilExAssignment::PEER_REVIEW_VALID_NONE);
+
+ $a_ass->setPeerReviewFileUpload($a_input["peer_file"]);
+ $a_ass->setPeerReviewChars($a_input["peer_char"]);
+ $a_ass->setPeerReviewText($a_input["peer_text"]);
+ $a_ass->setPeerReviewRating($a_input["peer_rating"]);
+ $a_ass->setPeerReviewCriteriaCatalogue($a_input["crit_cat"] > 0
+ ? $a_input["crit_cat"]
+ : null);
+
+ $a_ass->update();
+
+ $this->importPeerReviewFormToAssignmentReminders($a_input, $a_ass->getId());
+ }
+
+ protected function updatePeerReviewObject()
+ {
+ $tpl = $this->tpl;
+ $lng = $this->lng;
+ $ilCtrl = $this->ctrl;
+ $ilTabs = $this->tabs;
+
+ $form = $this->initPeerReviewForm();
+ $input = $this->processPeerReviewForm($form);
+ if (is_array($input)) {
+ $this->importPeerReviewFormToAssignment($this->assignment, $input);
+ ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true);
+ $ilCtrl->redirect($this, "editPeerReview");
+ } else {
+ $this->setAssignmentHeader();
+ $ilTabs->activateTab("peer_settings");
+
+ $form->setValuesByPost();
+ $this->handleDisabledPeerFields($form);
+ $tpl->setContent($form->getHtml());
+ }
+ }
+
+
+ //
+ // TEAM
+ //
+
+ /**
+ * @param $a_num_teams integer
+ * @param $a_min_participants integer
+ * @param $a_max_participants integer
+ * @return array
+ */
+ public function validationTeamsFormation($a_num_teams, $a_min_participants, $a_max_participants)
+ {
+ $total_members = $this->getExerciseTotalMembers();
+ $number_of_teams = $a_num_teams;
+
+ if ($number_of_teams) {
+ $members_per_team = round($total_members / $a_num_teams);
+ } else {
+ if ($a_min_participants) {
+ $number_of_teams = round($total_members / $a_min_participants);
+ $participants_extra_team = $total_members % $a_min_participants;
+ if ($participants_extra_team > $number_of_teams) {
+ //Can't create teams with this minimum of participants.
+ $message = sprintf($this->lng->txt("exc_team_minimal_too_big"), $a_min_participants);
+ return array("status" => "error", "msg" => $message, "field" => "min_participants_team");
+ }
+ }
+ $members_per_team = 0;
+ }
+
+ if ($a_min_participants > $a_max_participants) {
+ $message = $this->lng->txt("exc_team_min_big_than_max");
+ return array("status" => "error", "msg" => $message, "field" => "max_participants_team");
+ }
+
+ if ($a_max_participants > 0 && $members_per_team > $a_max_participants) {
+ $message = sprintf($this->lng->txt("exc_team_max_small_than_members"), $a_max_participants, $members_per_team);
+ return array("status" => "error", "msg" => $message, "field" => "max_participants_team");
+ }
+
+ if ($members_per_team > 0 && $members_per_team < $a_min_participants) {
+ $message = sprintf($this->lng->txt("exc_team_min_small_than_members"), $a_min_participants, $members_per_team);
+ return array("status" => "error", "msg" => $message, "field" => "min_participants_team");
+ }
+
+ return array("status" => "success", "msg" => "");
+ }
+
+ /**
+ * Get the total number of exercise members
+ * @return int
+ */
+ public function getExerciseTotalMembers()
+ {
+ $exercise = new ilObjExercise($this->exercise_id, false);
+ $exc_members = new ilExerciseMembers($exercise);
+
+ return count($exc_members->getMembers());
+ }
+
+ /**
+ * @param ilExAssignment $a_assignment
+ * @param array $a_input
+ */
+ public function generateTeams(ilExAssignment $a_assignment, $a_input)
+ {
+ $ass_type = $a_assignment->getAssignmentType();
+ if ($ass_type->usesTeams() &&
+ $a_input['team_creator'] == ilExAssignment::TEAMS_FORMED_BY_TUTOR) {
+ if ($a_input['team_creation'] == ilExAssignment::TEAMS_FORMED_BY_RANDOM) {
+ $number_teams = $a_input['number_teams'];
+ if (count(ilExAssignmentTeam::getAssignmentTeamMap($a_assignment->getId())) == 0) {
+ $ass_team = new ilExAssignmentTeam();
+ $ass_team->createRandomTeams($this->exercise_id, $a_assignment->getId(), $number_teams, $a_input['min_participants_team']);
}
- $rd_creation_random = new ilRadioOption(
- $lng->txt("exc_team_by_random"),
- ilExAssignment::TEAMS_FORMED_BY_RANDOM,
- $lng->txt("exc_team_by_random_info")."
".$lng->txt("exc_total_members").": ".$this->getExerciseTotalMembers().$add_info
- );
- $rd_creation_method->addOption($rd_creation_random);
-
- $number_teams = new ilNumberInputGUI($lng->txt("exc_num_teams"), "number_teams");
- $number_teams->setSize(3);
- $number_teams->setMinValue(1);
- $number_teams->setMaxValue($this->getExerciseTotalMembers());
- $number_teams->setRequired(true);
- $number_teams->setSuffix($lng->txt("exc_team_assignment_adopt_teams"));
- $rd_creation_random->addSubItem($number_teams);
-
- $min_team_participants = new ilNumberInputGUI($lng->txt("exc_min_team_participants"), "min_participants_team");
- $min_team_participants->setSize(3);
- $min_team_participants->setMinValue(1);
- $min_team_participants->setMaxValue($this->getExerciseTotalMembers());
- $min_team_participants->setRequired(true);
- $min_team_participants->setSuffix($lng->txt("exc_participants"));
- $rd_creation_random->addSubItem($min_team_participants);
-
- $max_team_participants = new ilNumberInputGUI($lng->txt("exc_max_team_participants"), "max_participants_team");
- $max_team_participants->setSize(3);
- $max_team_participants->setMinValue(1);
- $max_team_participants->setMaxValue($this->getExerciseTotalMembers());
- $max_team_participants->setRequired(true);
- $max_team_participants->setSuffix($lng->txt("exc_participants"));
- $rd_creation_random->addSubItem($max_team_participants);
-
- $options = ilExAssignmentTeam::getAdoptableTeamAssignments($this->exercise_id);
- if(count($options))
- {
- $radio_assignment = new ilRadioOption(
- $lng->txt("exc_team_by_assignment"),
- ilExAssignment::TEAMS_FORMED_BY_ASSIGNMENT,
- $lng->txt("exc_team_by_assignment_info")
- );
-
- $radio_assignment_adopt = new ilRadioGroupInputGUI($lng->txt("exc_assignment"), "ass_adpt");
- $radio_assignment_adopt->setRequired(true);
- $radio_assignment_adopt->addOption(new ilRadioOption($lng->txt("exc_team_assignment_adopt_none"), -1));
-
- foreach($options as $id => $item)
- {
- $option = new ilRadioOption($item["title"], $id);
- $option->setInfo($lng->txt("exc_team_assignment_adopt_teams").": ".$item["teams"]);
- $radio_assignment_adopt->addOption($option);
- }
- $radio_assignment->addSubItem($radio_assignment_adopt);
- $rd_creation_method->addOption($radio_assignment);
- }
-
- $radio_tutors->addSubItem($rd_creation_method);
- }
- $rd_team->addOption($radio_participants);
- $rd_team->addOption($radio_tutors);
- /*if(!$has_teams) {
- $rd_team->addOption($radio_assignment);
- }*/
- $form->addItem($rd_team);
-
- if($has_teams)
- {
- $rd_team->setDisabled(true);
- }
- }
-
- // mandatory
- $cb = new ilCheckboxInputGUI($lng->txt("exc_mandatory"), "mandatory");
- $cb->setInfo($lng->txt("exc_mandatory_info"));
- $cb->setChecked(true);
- $form->addItem($cb);
-
- // Work Instructions
- $sub_header = new ilFormSectionHeaderGUI();
- $sub_header->setTitle($lng->txt("exc_work_instructions"), "work_instructions");
- $form->addItem($sub_header);
-
- $desc_input = new ilTextAreaInputGUI($lng->txt("exc_instruction"), "instruction");
- $desc_input->setRows(20);
- $desc_input->setUseRte(true);
- $desc_input->setRteTagSet("mini");
- $form->addItem($desc_input);
-
- // files
- if ($a_mode == "create")
- {
- $files = new ilFileWizardInputGUI($lng->txt('objs_file'),'files');
- $files->setFilenames(array(0 => ''));
- $form->addItem($files);
- }
-
- // Schedule
- $sub_header = new ilFormSectionHeaderGUI();
- $sub_header->setTitle($lng->txt("exc_schedule"), "schedule");
- $form->addItem($sub_header);
-
- // start time
- $start_date = new ilDateTimeInputGUI($lng->txt("exc_start_time"), "start_time");
- $start_date->setShowTime(true);
- $form->addItem($start_date);
-
- // Deadline Mode
- $radg = new ilRadioGroupInputGUI($lng->txt("exc_deadline"), "deadline_mode");
- $radg->setValue(0);
- $op1 = new ilRadioOption($lng->txt("exc_fixed_date"), 0, $lng->txt("exc_fixed_date_info"));
- $radg->addOption($op1);
- $op2 = new ilRadioOption($lng->txt("exc_relative_date"), 1, $lng->txt("exc_relative_date_info"));
- $radg->addOption($op2);
- $form->addItem($radg);
-
- // Deadline fixed date
- $deadline = new ilDateTimeInputGUI($lng->txt("date"), "deadline");
- $deadline->setShowTime(true);
- $op1->addSubItem($deadline);
-
- // extended Deadline
- $deadline2 = new ilDateTimeInputGUI($lng->txt("exc_deadline_extended"), "deadline2");
- $deadline2->setInfo($lng->txt("exc_deadline_extended_info"));
- $deadline2->setShowTime(true);
- $deadline->addSubItem($deadline2);
-
-
- // submit reminder
- $rmd_submit = new ilCheckboxInputGUI($this->lng->txt("exc_reminder_submit_setting"), "rmd_submit_status");
-
- $rmd_submit_start = new ilNumberInputGUI($this->lng->txt("exc_reminder_start"), "rmd_submit_start");
- $rmd_submit_start->setSize(3);
- $rmd_submit_start->setMaxLength(3);
- $rmd_submit_start->setSuffix($lng->txt('days'));
- $rmd_submit_start->setInfo($this->lng->txt("exc_reminder_start_info"));
- $rmd_submit_start->setRequired(true);
- $rmd_submit_start->setMinValue(1);
- $rmd_submit->addSubItem($rmd_submit_start);
-
- $rmd_submit_frequency = new ilNumberInputGUI($this->lng->txt("exc_reminder_frequency"), "rmd_submit_freq");
- $rmd_submit_frequency->setSize(3);
- $rmd_submit_frequency->setMaxLength(3);
- $rmd_submit_frequency->setSuffix($lng->txt('days'));
- $rmd_submit_frequency->setRequired(true);
- $rmd_submit_frequency->setMinValue(1);
- $rmd_submit->addSubItem($rmd_submit_frequency);
-
- $rmd_submit_end = new ilDateTimeInputGUI($lng->txt("exc_reminder_end"), "rmd_submit_end");
- $rmd_submit_end->setRequired(true);
- $rmd_submit->addSubItem($rmd_submit_end);
-
- $rmd_submit->addSubItem($this->addMailTemplatesRadio(ilExAssignmentReminder::SUBMIT_REMINDER));
-
- // grade reminder
- $rmd_grade = new ilCheckboxInputGUI($this->lng->txt("exc_reminder_grade_setting"), "rmd_grade_status");
-
- $rmd_grade_frequency = new ilNumberInputGUI($this->lng->txt("exc_reminder_frequency"), "rmd_grade_freq");
- $rmd_grade_frequency->setSize(3);
- $rmd_grade_frequency->setMaxLength(3);
- $rmd_grade_frequency->setSuffix($lng->txt('days'));
- $rmd_grade_frequency->setRequired(true);
- $rmd_grade_frequency->setMinValue(1);
- $rmd_grade->addSubItem($rmd_grade_frequency);
-
- $rmd_grade_end = new ilDateTimeInputGUI($lng->txt("exc_reminder_end"), "rmd_grade_end");
- $rmd_grade_end->setRequired(true);
- $rmd_grade->addSubItem($rmd_grade_end);
-
- $rmd_grade->addSubItem($this->addMailTemplatesRadio(ilExAssignmentReminder::GRADE_REMINDER));
-
- $form->addItem($rmd_submit);
- $form->addItem($rmd_grade);
-
- // relative deadline
- $ti = new ilNumberInputGUI($lng->txt("days"), "relative_deadline");
- $ti->setMaxLength(3);
- $ti->setSize(3);
- $op2->addSubItem($ti);
-
-
- // max number of files
- if($ass_type->usesFileUpload())
- {
- $sub_header = new ilFormSectionHeaderGUI();
- $sub_header->setTitle($ass_type->getTitle());
- $form->addItem($sub_header);
- $max_file_tgl = new ilCheckboxInputGUI($lng->txt("exc_max_file_tgl"), "max_file_tgl");
- $form->addItem($max_file_tgl);
-
- $max_file = new ilNumberInputGUI($lng->txt("exc_max_file"), "max_file");
- $max_file->setInfo($lng->txt("exc_max_file_info"));
- $max_file->setRequired(true);
- $max_file->setSize(3);
- $max_file->setMinValue(1);
- $max_file_tgl->addSubItem($max_file);
- }
-
- // after submission
- $sub_header = new ilFormSectionHeaderGUI();
- $sub_header->setTitle($lng->txt("exc_after_submission"), "after_submission");
- $form->addItem($sub_header);
- if (!$ass_type->usesTeams())
- {
- // peer review
- $peer = new ilCheckboxInputGUI($lng->txt("exc_peer_review"), "peer");
- $peer->setInfo($lng->txt("exc_peer_review_ass_setting_info"));
- $form->addItem($peer);
- }
-
-
- // global feedback
-
- $fb = new ilCheckboxInputGUI($lng->txt("exc_global_feedback_file"), "fb");
- $form->addItem($fb);
-
- $fb_file = new ilFileInputGUI($lng->txt("file"), "fb_file");
- $fb_file->setRequired(true); // will be disabled on update if file exists - see getAssignmentValues()
- // $fb_file->setAllowDeletion(true); makes no sense if required (overwrite or keep)
- $fb->addSubItem($fb_file);
-
- $fb_date = new ilRadioGroupInputGUI($lng->txt("exc_global_feedback_file_date"), "fb_date");
- $fb_date->setRequired(true);
- $fb_date->addOption(new ilRadioOption($lng->txt("exc_global_feedback_file_date_deadline"), ilExAssignment::FEEDBACK_DATE_DEADLINE));
- $fb_date->addOption(new ilRadioOption($lng->txt("exc_global_feedback_file_date_upload"), ilExAssignment::FEEDBACK_DATE_SUBMISSION));
-
- //Extra radio option with date selection
- $fb_date_custom_date = new ilDateTimeInputGUI($lng->txt("date"),"fb_date_custom");
- $fb_date_custom_date->setRequired(true);
- $fb_date_custom_date->setShowTime(true);
- $fb_date_custom_option = new ilRadioOption($lng->txt("exc_global_feedback_file_after_date"), ilExAssignment::FEEDBACK_DATE_CUSTOM);
- $fb_date_custom_option->addSubItem($fb_date_custom_date);
- $fb_date->addOption($fb_date_custom_option);
-
-
- $fb->addSubItem($fb_date);
-
- $fb_cron = new ilCheckboxInputGUI($lng->txt("exc_global_feedback_file_cron"), "fb_cron");
- $fb_cron->setInfo($lng->txt("exc_global_feedback_file_cron_info"));
- $fb->addSubItem($fb_cron);
-
-
- if ($a_mode == "create")
- {
- $form->addCommandButton("saveAssignment", $lng->txt("save"));
- $form->addCommandButton("listAssignments", $lng->txt("cancel"));
- }
- else
- {
- $form->addCommandButton("updateAssignment", $lng->txt("save"));
- $form->addCommandButton("listAssignments", $lng->txt("cancel"));
- }
-
- return $form;
- }
-
- public function addMailTemplatesRadio($a_reminder_type)
- {
- global $DIC;
-
- $post_var = "rmd_".$a_reminder_type."_template_id";
-
- $r_group = new ilRadioGroupInputGUI($this->lng->txt("exc_reminder_mail_template"), $post_var);
- $r_group->setRequired(true);
- $r_group->addOption(new ilRadioOption($this->lng->txt("exc_reminder_mail_no_tpl"), 0));
-
- switch ($a_reminder_type)
- {
- case ilExAssignmentReminder::SUBMIT_REMINDER:
- include_once "Modules/Exercise/classes/class.ilExcMailTemplateSubmitReminderContext.php";
- $context = new ilExcMailTemplateSubmitReminderContext();
- break;
- case ilExAssignmentReminder::GRADE_REMINDER:
- include_once "Modules/Exercise/classes/class.ilExcMailTemplateGradeReminderContext.php";
- $context = new ilExcMailTemplateGradeReminderContext();
- break;
- case ilExAssignmentReminder::FEEDBACK_REMINDER:
- include_once "Modules/Exercise/classes/class.ilExcMailTemplatePeerReminderContext.php";
- $context = new ilExcMailTemplatePeerReminderContext();
- break;
- default:
- exit();
- }
-
- /** @var \ilMailTemplateService $templateService */
- $templateService = $DIC['mail.texttemplates.service'];
- foreach ($templateService->loadTemplatesForContextId((string)$context->getId()) as $template) {
- $r_group->addOption(new ilRadioOption($template->getTitle(), $template->getTplId()));
- }
-
- return $r_group;
- }
-
- /**
- * Custom form validation
- *
- * @param ilPropertyFormGUI $a_form
- * @return array
- */
- protected function processForm(ilPropertyFormGUI $a_form)
- {
- $lng = $this->lng;
-
- $protected_peer_review_groups = false;
-
- if($this->assignment)
- {
- if($this->assignment->getPeerReview())
- {
- include_once "Modules/Exercise/classes/class.ilExPeerReview.php";
- $peer_review = new ilExPeerReview($this->assignment);
- if($peer_review->hasPeerReviewGroups())
- {
- $protected_peer_review_groups = true;
- }
- }
-
- if($this->assignment->getFeedbackFile())
- {
- $a_form->getItemByPostVar("fb_file")->setRequired(false); // #15467
- }
- }
-
- $valid = $a_form->checkInput();
-
- if($protected_peer_review_groups)
- {
- // checkInput() will add alert to disabled fields
- $a_form->getItemByPostVar("deadline")->setAlert(null);
- $a_form->getItemByPostVar("deadline2")->setAlert(null);
- }
-
- if($valid)
- {
- $type = $a_form->getInput("type");
- $ass_type = $this->types->getById($type);
-
- // dates
-
- $time_start = $a_form->getItemByPostVar("start_time")->getDate();
- $time_start = $time_start
- ? $time_start->get(IL_CAL_UNIX)
- : null;
-
- $time_deadline = $a_form->getItemByPostVar("deadline")->getDate();
- $time_deadline = $time_deadline
- ? $time_deadline->get(IL_CAL_UNIX)
- : null;
- $time_deadline_ext = $a_form->getItemByPostVar("deadline2")->getDate();
- $time_deadline_ext = $time_deadline_ext
- ? $time_deadline_ext->get(IL_CAL_UNIX)
- : null;
- $time_fb_custom_date = $a_form->getItemByPostVar("fb_date_custom")->getDate();
- $time_fb_custom_date = $time_fb_custom_date
- ? $time_fb_custom_date->get(IL_CAL_UNIX)
- : null;
-
- $reminder_submit_end_date = $a_form->getItemByPostVar("rmd_submit_end")->getDate();
- $reminder_submit_end_date = $reminder_submit_end_date
- ? $reminder_submit_end_date->get(IL_CAL_UNIX)
- : null;
-
- $reminder_grade_end_date = $a_form->getItemByPostVar("rmd_grade_end")->getDate();
- $reminder_grade_end_date = $reminder_grade_end_date
- ? $reminder_grade_end_date->get(IL_CAL_UNIX)
- : null;
-
- $time_deadline = null;
- $time_deadline_ext = null;
-
- if ((int) $a_form->getInput("deadline_mode") == ilExAssignment::DEADLINE_ABSOLUTE)
- {
- $time_deadline = $a_form->getItemByPostVar("deadline")->getDate();
- $time_deadline = $time_deadline
- ? $time_deadline->get(IL_CAL_UNIX)
- : null;
- $time_deadline_ext = $a_form->getItemByPostVar("deadline2")->getDate();
- $time_deadline_ext = $time_deadline_ext
- ? $time_deadline_ext->get(IL_CAL_UNIX)
- : null;
- }
-
-
- // handle disabled elements
- if($protected_peer_review_groups)
- {
- $time_deadline = $this->assignment->getDeadline();
- $time_deadline_ext = $this->assignment->getExtendedDeadline();
- }
-
- // no deadline?
- if(!$time_deadline)
- {
- // peer review
- if(!$protected_peer_review_groups &&
- $a_form->getInput("peer"))
- {
- $a_form->getItemByPostVar("peer")
- ->setAlert($lng->txt("exc_needs_fixed_deadline"));
- $valid = false;
- }
- // global feedback
- if($a_form->getInput("fb") &&
- $a_form->getInput("fb_date") == ilExAssignment::FEEDBACK_DATE_DEADLINE)
- {
- $a_form->getItemByPostVar("fb")
- ->setAlert($lng->txt("exc_needs_deadline"));
- $valid = false;
- }
- }
- else
- {
- // #18269
- if($a_form->getInput("peer"))
- {
- $time_deadline_max = max($time_deadline, $time_deadline_ext);
- $peer_dl = $this->assignment // #18380
- ? $this->assignment->getPeerReviewDeadline()
- : null;
- if($peer_dl && $peer_dl < $time_deadline_max)
- {
- $a_form->getItemByPostVar($peer_dl < $time_deadline_ext
- ? "deadline2"
- : "deadline")
- ->setAlert($lng->txt("exc_peer_deadline_mismatch"));
- $valid = false;
- }
- }
-
- if($time_deadline_ext && $time_deadline_ext < $time_deadline)
- {
- $a_form->getItemByPostVar("deadline2")
- ->setAlert($lng->txt("exc_deadline_ext_mismatch"));
- $valid = false;
- }
-
- $time_deadline_min = $time_deadline_ext
- ? min($time_deadline, $time_deadline_ext)
- : $time_deadline;
- $time_deadline_max = max($time_deadline, $time_deadline_ext);
-
- // start > any deadline ?
- if($time_start && $time_deadline_min && $time_start > $time_deadline_min)
- {
- $a_form->getItemByPostVar("start_time")
- ->setAlert($lng->txt("exc_start_date_should_be_before_end_date"));
- $valid = false;
- }
- }
-
- if($ass_type->usesTeams())
- {
- if ($a_form->getInput("team_creation") == ilExAssignment::TEAMS_FORMED_BY_RANDOM &&
- $a_form->getInput("team_creator") == ilExAssignment::TEAMS_FORMED_BY_TUTOR)
- {
- $team_validation = $this->validationTeamsFormation(
- $a_form->getInput("number_teams"),
- $a_form->getInput("min_participants_team"),
- $a_form->getInput("max_participants_team")
- );
- if ($team_validation['status'] == 'error')
- {
- $a_form->getItemByPostVar("team_creation")
- ->setAlert($team_validation['msg']);
- $a_form->getItemByPostVar($team_validation["field"])
- ->setAlert($lng->txt("exc_value_can_not_set"));
- $valid = false;
- }
- }
- }
-
- if($valid)
- {
- $res = array(
- // core
- "type" => $a_form->getInput("type")
- ,"title" => trim($a_form->getInput("title"))
- ,"instruction" => trim($a_form->getInput("instruction"))
- ,"mandatory" => $a_form->getInput("mandatory")
- // dates
- ,"start" => $time_start
- ,"deadline" => $time_deadline
- ,"deadline_ext" => $time_deadline_ext
- ,"max_file" => $a_form->getInput("max_file_tgl")
- ? $a_form->getInput("max_file")
- : null
- );
-
- if($a_form->getInput("team_creator") == ilExAssignment::TEAMS_FORMED_BY_TUTOR)
- {
- $res['team_creator'] = $a_form->getInput("team_creator");
- $res["team_creation"] = $a_form->getInput("team_creation");
-
- if($a_form->getInput("team_creation") == ilExAssignment::TEAMS_FORMED_BY_RANDOM)
- {
- $res["number_teams"] = $a_form->getInput("number_teams");
- $res["min_participants_team"] = $a_form->getInput("min_participants_team");
- $res["max_participants_team"] = $a_form->getInput("max_participants_team");
- }
- else if($a_form->getInput("team_creation") == ilExAssignment::TEAMS_FORMED_BY_ASSIGNMENT)
- {
- $res['ass_adpt'] = $a_form->getInput("ass_adpt");
- }
- }
-
- // portfolio template
- //if($a_form->getInput("template_id") && $a_form->getInput("template"))
- //{
- // $res['template_id'] = $a_form->getInput("template_id");
- //}
-
- // text limitations
- /*
- if($a_form->getInput("limit_characters"))
- {
- $res['limit_characters'] = $a_form->getInput("limit_characters");
- }
- if($a_form->getInput("limit_characters") && $a_form->getInput("max_char_limit"))
- {
- $res['max_char_limit'] = $a_form->getInput("max_char_limit");
- }
- if($a_form->getInput("limit_characters") && $a_form->getInput("min_char_limit"))
- {
- $res['min_char_limit'] = $a_form->getInput("min_char_limit");
-
- }*/
-
-
- $res["deadline_mode"] = $a_form->getInput("deadline_mode");
-
- if ($res["deadline_mode"] == ilExAssignment::DEADLINE_RELATIVE)
- {
- $res["relative_deadline"] = $a_form->getInput("relative_deadline");
- }
-
- // peer
- if($a_form->getInput("peer") ||
- $protected_peer_review_groups)
- {
- $res["peer"] = true;
- }
-
- // files
- if(is_array($_FILES["files"]))
- {
- // #15994 - we are keeping the upload files array structure
- // see ilFSStorageExercise::uploadAssignmentFiles()
- $res["files"] = $_FILES["files"];
- }
-
- // global feedback
- if($a_form->getInput("fb"))
- {
- $res["fb"] = true;
- $res["fb_cron"] = $a_form->getInput("fb_cron");
- $res["fb_date"] = $a_form->getInput("fb_date");
- $res["fb_date_custom"] = $time_fb_custom_date;
-
- if($_FILES["fb_file"]["tmp_name"])
- {
- $res["fb_file"] = $_FILES["fb_file"];
- }
- }
- if($a_form->getInput("rmd_submit_status"))
- {
- $res["rmd_submit_status"] = true;
- $res["rmd_submit_start"] = $a_form->getInput("rmd_submit_start");
- $res["rmd_submit_freq"] = $a_form->getInput("rmd_submit_freq");
- $res["rmd_submit_end"] = $reminder_submit_end_date;
- $res["rmd_submit_template_id"] = $a_form->getInput("rmd_submit_template_id");
- }
- if($a_form->getInput("rmd_grade_status"))
- {
- $res["rmd_grade_status"] = true;
- $res["rmd_grade_freq"] = $a_form->getInput("rmd_grade_freq");
- $res["rmd_grade_end"] = $reminder_grade_end_date;
- $res["rmd_grade_template_id"] = $a_form->getInput("rmd_grade_template_id");
- }
-
- return $res;
- }
- else
- {
- ilUtil::sendFailure($lng->txt("form_input_not_valid"));
- }
- }
- }
-
- /**
- * Import form values to assignment
- *
- * @param ilExAssignment $a_ass
- * @param array $a_input
- */
- protected function importFormToAssignment(ilExAssignment $a_ass, array $a_input)
- {
- $is_create = !(bool)$a_ass->getId();
-
- $a_ass->setTitle($a_input["title"]);
- $a_ass->setInstruction($a_input["instruction"]);
- $a_ass->setMandatory($a_input["mandatory"]);
-
- $a_ass->setStartTime($a_input["start"]);
- $a_ass->setDeadline($a_input["deadline"]);
- $a_ass->setExtendedDeadline($a_input["deadline_ext"]);
- $a_ass->setDeadlineMode($a_input["deadline_mode"]);
- $a_ass->setRelativeDeadline($a_input["relative_deadline"]);
-
- $a_ass->setMaxFile($a_input["max_file"]);
- $a_ass->setTeamTutor($a_input["team_creator"]);
-
- //$a_ass->setPortfolioTemplateId($a_input['template_id']);
-
- //$a_ass->setMinCharLimit($a_input['min_char_limit']);
- //$a_ass->setMaxCharLimit($a_input['max_char_limit']);
-
- $a_ass->setPeerReview((bool)$a_input["peer"]);
-
- // peer review default values (on separate form)
- if($is_create)
- {
- $a_ass->setPeerReviewMin(2);
- $a_ass->setPeerReviewSimpleUnlock(false);
- $a_ass->setPeerReviewValid(ilExAssignment::PEER_REVIEW_VALID_NONE);
- $a_ass->setPeerReviewPersonalized(false);
- $a_ass->setPeerReviewFileUpload(false);
- $a_ass->setPeerReviewText(true);
- $a_ass->setPeerReviewRating(true);
- }
-
- if($a_input["fb"])
- {
- $a_ass->setFeedbackCron($a_input["fb_cron"]); // #13380
- $a_ass->setFeedbackDate($a_input["fb_date"]);
- $a_ass->setFeedbackDateCustom($a_input["fb_date_custom"]);
- }
-
- // id needed for file handling
- if($is_create)
- {
- $a_ass->save();
-
- // #15994 - assignment files
- if(is_array($a_input["files"]))
- {
- $a_ass->uploadAssignmentFiles($a_input["files"]);
- }
- }
- else
- {
- // remove global feedback file?
- if(!$a_input["fb"])
- {
- $a_ass->deleteGlobalFeedbackFile();
- $a_ass->setFeedbackFile(null);
- }
-
- $a_ass->update();
- }
-
- // add global feedback file?
- if($a_input["fb"])
- {
- if(is_array($a_input["fb_file"]))
- {
- $a_ass->handleGlobalFeedbackFileUpload($a_input["fb_file"]);
- $a_ass->update();
- }
- }
- $this->importFormToAssignmentReminders($a_input, $a_ass->getId());
- }
-
- protected function importFormToAssignmentReminders($a_input, $a_ass_id)
- {
- $reminder = new ilExAssignmentReminder($this->exercise_id, $a_ass_id, ilExAssignmentReminder::SUBMIT_REMINDER);
- $this->saveReminderData($reminder, $a_input);
-
- $reminder = new ilExAssignmentReminder($this->exercise_id, $a_ass_id, ilExAssignmentReminder::GRADE_REMINDER);
- $this->saveReminderData($reminder, $a_input);
-
- }
-
- //todo maybe we can refactor this method to use only one importFormToReminders
- protected function importPeerReviewFormToAssignmentReminders($a_input, $a_ass_id)
- {
- $reminder = new ilExAssignmentReminder($this->exercise_id, $a_ass_id, ilExAssignmentReminder::FEEDBACK_REMINDER);
- $this->saveReminderData($reminder, $a_input);
- }
-
- protected function saveReminderData(ilExAssignmentReminder $reminder, $a_input)
- {
- if($reminder->getReminderStatus() == NULL) {
- $action = "save";
- } else {
- $action = "update";
- }
- $type = $reminder->getReminderType();
- $reminder->setReminderStatus((bool)$a_input["rmd_".$type."_status"]);
- $reminder->setReminderStart((int)$a_input["rmd_".$type."_start"]);
- $reminder->setReminderEnd((int)$a_input["rmd_".$type."_end"]);
- $reminder->setReminderFrequency((int)$a_input["rmd_".$type."_freq"]);
- $reminder->setReminderMailTemplate((int)$a_input["rmd_".$type."_template_id"]);
- $reminder->{$action}();
- }
-
- /**
- * Save assignment
- *
- */
- public function saveAssignmentObject()
- {
- $tpl = $this->tpl;
- $lng = $this->lng;
- $ilCtrl = $this->ctrl;
-
- // #16163 - ignore ass id from request
- $this->assignment = null;
-
- $form = $this->initAssignmentForm((int)$_POST["type"], "create");
- $input = $this->processForm($form);
- if(is_array($input))
- {
- $ass = new ilExAssignment();
- $ass->setExerciseId($this->exercise_id);
- $ass->setType($input["type"]);
- $ass_type = $ass->getAssignmentType();
- $ass_type_gui = $this->type_guis->getById($ass->getType());
-
- $this->importFormToAssignment($ass, $input);
-
- $this->generateTeams($ass, $input);
- ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true);
-
- $ass_type_gui->importFormToAssignment($ass, $form);
- $ass->update();
-
- ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true);
-
- // because of sub-tabs we stay on settings screen
- $ilCtrl->setParameter($this, "ass_id", $ass->getId());
- $ilCtrl->redirect($this, "editAssignment");
- }
- else
- {
- $form->setValuesByPost();
- $tpl->setContent($form->getHtml());
- }
- }
-
- /**
- * Edit assignment
- */
- function editAssignmentObject()
- {
- $ilTabs = $this->tabs;
- $tpl = $this->tpl;
-
- $this->setAssignmentHeader();
- $ilTabs->activateTab("ass_settings");
-
- $form = $this->initAssignmentForm($this->assignment->getType(), "edit");
- $this->getAssignmentValues($form);
- $tpl->setContent($form->getHTML());
- }
-
- /**
- * Get current values for assignment from
- */
- public function getAssignmentValues(ilPropertyFormGUI $a_form)
- {
- $lng = $this->lng;
- $ilCtrl = $this->ctrl;
-
- $ass_type_gui = $this->type_guis->getById($this->assignment->getType());
-
- $values = array();
- $values["type"] = $this->assignment->getType();
- $values["title"] = $this->assignment->getTitle();
- $values["mandatory"] = $this->assignment->getMandatory();
- $values["instruction"] = $this->assignment->getInstruction();
- //$values['template_id'] = $this->assignment->getPortfolioTemplateId();
-
- //if($this->assignment->getPortfolioTemplateId())
- //{
- // $values["template"] = 1;
- //}
-
- /*if($this->assignment->getMinCharLimit())
- {
- $values['limit_characters'] = 1;
- $values['min_char_limit'] = $this->assignment->getMinCharLimit();
- }
- if($this->assignment->getMaxCharLimit())
- {
- $values['limit_characters'] = 1;
- $values['max_char_limit'] = $this->assignment->getMaxCharLimit();
- }*/
-
- if ($this->assignment->getStartTime())
- {
- $values["start_time"] = new ilDateTime($this->assignment->getStartTime(), IL_CAL_UNIX);
- }
-
- if ($this->assignment->getAssignmentType()->usesFileUpload())
- {
- if ($this->assignment->getMaxFile())
- {
- $values["max_file_tgl"] = true;
- $values["max_file"] = $this->assignment->getMaxFile();
- }
- }
-
- if($this->assignment->getAssignmentType()->usesTeams())
- {
- $values["team_creator"] = $this->assignment->getTeamTutor();
- }
-
- if ($this->assignment->getFeedbackDateCustom())
- {
- $values["fb_date_custom"] = new ilDateTime($this->assignment->getFeedbackDateCustom(), IL_CAL_UNIX);
- }
-
- //Reminders
- $rmd_sub = new ilExAssignmentReminder($this->exercise_id, $this->assignment->getId(), ilExAssignmentReminder::SUBMIT_REMINDER);
- if($rmd_sub->getReminderStatus())
- {
- $values["rmd_submit_status"] = $rmd_sub->getReminderStatus();
- $values["rmd_submit_start"] = $rmd_sub->getReminderStart();
- $values["rmd_submit_end"] = new ilDateTime($rmd_sub->getReminderEnd(), IL_CAL_UNIX);
- $values["rmd_submit_freq"] = $rmd_sub->getReminderFrequency();
- $values["rmd_submit_template_id"] = $rmd_sub->getReminderMailTemplate();
- }
-
- $rmd_grade = new ilExAssignmentReminder($this->exercise_id, $this->assignment->getId(), ilExAssignmentReminder::GRADE_REMINDER);
- if($rmd_grade->getReminderStatus())
- {
- $values["rmd_grade_status"] = $rmd_grade->getReminderStatus();
- $values["rmd_grade_end"] = new ilDateTime($rmd_grade->getReminderEnd(), IL_CAL_UNIX);
- $values["rmd_grade_freq"] = $rmd_grade->getReminderFrequency();
- $values["rmd_grade_template_id"] = $rmd_grade->getReminderMailTemplate();
- }
-
- $type_values = $ass_type_gui->getFormValuesArray($this->assignment);
- $values = array_merge($values, $type_values);
-
-
- $values["deadline_mode"] = $this->assignment->getDeadlineMode();
- $values["relative_deadline"] = $this->assignment->getRelativeDeadline();
-
- $a_form->setValuesByArray($values);
-
- // global feedback
- if($this->assignment->getFeedbackFile())
- {
- $a_form->getItemByPostVar("fb")->setChecked(true);
- $a_form->getItemByPostVar("fb_file")->setValue(basename($this->assignment->getGlobalFeedbackFilePath()));
- $a_form->getItemByPostVar("fb_file")->setRequired(false); // #15467
- $a_form->getItemByPostVar("fb_file")->setInfo(
- // #16400
- ''.
- $lng->txt("download").''
- );
- }
- $a_form->getItemByPostVar("fb_cron")->setChecked($this->assignment->hasFeedbackCron());
- $a_form->getItemByPostVar("fb_date")->setValue($this->assignment->getFeedbackDate());
-
- $this->handleDisabledFields($a_form, true);
- }
-
- protected function setDisabledFieldValues(ilPropertyFormGUI $a_form)
- {
- // dates
- if($this->assignment->getDeadline() > 0)
- {
- $edit_date = new ilDateTime($this->assignment->getDeadline(), IL_CAL_UNIX);
- $ed_item = $a_form->getItemByPostVar("deadline");
- $ed_item->setDate($edit_date);
-
- if($this->assignment->getExtendedDeadline() > 0)
- {
- $edit_date = new ilDateTime($this->assignment->getExtendedDeadline(), IL_CAL_UNIX);
- $ed_item = $a_form->getItemByPostVar("deadline2");
- $ed_item->setDate($edit_date);
- }
- }
-
- if($this->assignment->getPeerReview())
- {
- $a_form->getItemByPostVar("peer")->setChecked($this->assignment->getPeerReview());
- }
- }
-
- protected function handleDisabledFields(ilPropertyFormGUI $a_form, $a_force_set_values = false)
- {
- // potentially disabled elements are initialized here to re-use this
- // method after setValuesByPost() - see updateAssignmentObject()
-
- // team assignments do not support peer review
- // with no active peer review there is nothing to protect
- if(!$this->assignment->getAssignmentType()->usesTeams() &&
- $this->assignment->getPeerReview())
- {
- // #14450
- include_once "Modules/Exercise/classes/class.ilExPeerReview.php";
- $peer_review = new ilExPeerReview($this->assignment);
- if($peer_review->hasPeerReviewGroups())
- {
- // deadline(s) are past and must not change
- $a_form->getItemByPostVar("deadline")->setDisabled(true);
- $a_form->getItemByPostVar("deadline2")->setDisabled(true);
-
- $a_form->getItemByPostVar("peer")->setDisabled(true);
-
- $a_form->getItemByPostVar("deadline_mode")->setDisabled(true);
- }
- }
-
- if($a_force_set_values ||
- ($peer_review && $peer_review->hasPeerReviewGroups()))
- {
- $this->setDisabledFieldValues($a_form);
- }
- }
-
- /**
- * Update assignment
- *
- */
- public function updateAssignmentObject()
- {
- $tpl = $this->tpl;
- $lng = $this->lng;
- $ilCtrl = $this->ctrl;
- $ilTabs = $this->tabs;
-
- $form = $this->initAssignmentForm($this->assignment->getType(), "edit");
- $input = $this->processForm($form);
-
- $ass_type = $this->assignment->getType();
- $ass_type_gui = $this->type_guis->getById($ass_type);
-
- if(is_array($input))
- {
- $old_deadline = $this->assignment->getDeadline();
- $old_ext_deadline = $this->assignment->getExtendedDeadline();
-
- $this->importFormToAssignment($this->assignment, $input);
- $this->generateTeams($this->assignment, $input);
-
- $ass_type_gui->importFormToAssignment($this->assignment, $form);
- $this->assignment->update();
-
- $new_deadline = $this->assignment->getDeadline();
- $new_ext_deadline = $this->assignment->getExtendedDeadline();
-
- // if deadlines were changed
- if($old_deadline != $new_deadline ||
- $old_ext_deadline != $new_ext_deadline)
- {
- $this->assignment->recalculateLateSubmissions();
- }
-
- ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true);
- $ilCtrl->redirect($this, "editAssignment");
- }
- else
- {
- $this->setAssignmentHeader();
- $ilTabs->activateTab("ass_settings");
-
- $form->setValuesByPost();
- $this->handleDisabledFields($form);
- $tpl->setContent($form->getHtml());
- }
- }
-
- /**
- * Confirm assignments deletion
- */
- function confirmAssignmentsDeletionObject()
- {
- $ilCtrl = $this->ctrl;
- $tpl = $this->tpl;
- $lng = $this->lng;
-
- if (!is_array($_POST["id"]) || count($_POST["id"]) == 0)
- {
- ilUtil::sendFailure($lng->txt("no_checkbox"), true);
- $ilCtrl->redirect($this, "listAssignments");
- }
- else
- {
- include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php");
- $cgui = new ilConfirmationGUI();
- $cgui->setFormAction($ilCtrl->getFormAction($this));
- $cgui->setHeaderText($lng->txt("exc_conf_del_assignments"));
- $cgui->setCancel($lng->txt("cancel"), "listAssignments");
- $cgui->setConfirm($lng->txt("delete"), "deleteAssignments");
-
- foreach ($_POST["id"] as $i)
- {
- $cgui->addItem("id[]", $i, ilExAssignment::lookupTitle($i));
- }
-
- $tpl->setContent($cgui->getHTML());
- }
- }
-
- /**
- * Delete assignments
- */
- function deleteAssignmentsObject()
- {
- $ilCtrl = $this->ctrl;
- $lng = $this->lng;
-
- $delete = false;
- if (is_array($_POST["id"]))
- {
- foreach($_POST["id"] as $id)
- {
- $ass = new ilExAssignment(ilUtil::stripSlashes($id));
- $ass->delete();
- $delete = true;
- }
- }
-
- if ($delete)
- {
- ilUtil::sendSuccess($lng->txt("exc_assignments_deleted"), true);
- }
- $ilCtrl->setParameter($this, "ass_id", "");
- $ilCtrl->redirect($this, "listAssignments");
- }
-
- /**
- * Save assignments order
- */
- function saveAssignmentOrderObject()
- {
- $lng = $this->lng;
- $ilCtrl = $this->ctrl;
-
- ilExAssignment::saveAssOrderOfExercise($this->exercise_id, $_POST["order"]);
-
- ilUtil::sendSuccess($lng->txt("exc_saved_order"), true);
- $ilCtrl->redirect($this, "listAssignments");
- }
-
- /**
- * Order by deadline
- */
- function orderAssignmentsByDeadlineObject()
- {
- $lng = $this->lng;
- $ilCtrl = $this->ctrl;
-
- ilExAssignment::orderAssByDeadline($this->exercise_id);
-
- ilUtil::sendSuccess($lng->txt("exc_saved_order"), true);
- $ilCtrl->redirect($this, "listAssignments");
- }
-
- /**
- * Set assignment header
- */
- function setAssignmentHeader()
- {
- $ilTabs = $this->tabs;
- $lng = $this->lng;
- $ilCtrl = $this->ctrl;
- $tpl = $this->tpl;
- $ilHelp = $this->help;
-
- $tpl->setTitle($this->assignment->getTitle());
- $tpl->setDescription("");
-
- $ilTabs->clearTargets();
- $ilHelp->setScreenIdComponent("exc");
-
- $ilTabs->setBackTarget($lng->txt("back"),
- $ilCtrl->getLinkTarget($this, "listAssignments"));
-
- $ilTabs->addTab("ass_settings",
- $lng->txt("settings"),
- $ilCtrl->getLinkTarget($this, "editAssignment"));
-
- if(!$this->assignment->getAssignmentType()->usesTeams() &&
- $this->assignment->getPeerReview())
- {
- $ilTabs->addTab("peer_settings",
- $lng->txt("exc_peer_review"),
- $ilCtrl->getLinkTarget($this, "editPeerReview"));
- }
-
- $ilTabs->addTab("ass_files",
- $lng->txt("exc_instruction_files"),
- $ilCtrl->getLinkTargetByClass(array("ilexassignmenteditorgui", "ilexassignmentfilesystemgui"), "listFiles"));
- }
-
- public function downloadGlobalFeedbackFileObject()
- {
- $ilCtrl = $this->ctrl;
-
- if(!$this->assignment ||
- !$this->assignment->getFeedbackFile())
- {
- $ilCtrl->redirect($this, "returnToParent");
- }
-
- ilUtil::deliverFile($this->assignment->getGlobalFeedbackFilePath(), $this->assignment->getFeedbackFile());
- }
-
-
- //
- // PEER REVIEW
- //
-
- protected function initPeerReviewForm()
- {
- $ilCtrl = $this->ctrl;
- $lng = $this->lng;
-
- include_once("./Services/Form/classes/class.ilPropertyFormGUI.php");
- $form = new ilPropertyFormGUI();
- $form->setTitle($lng->txt("exc_peer_review"));
- $form->setFormAction($ilCtrl->getFormAction($this));
-
- $peer_min = new ilNumberInputGUI($lng->txt("exc_peer_review_min_number"), "peer_min");
- $peer_min->setInfo($lng->txt("exc_peer_review_min_number_info")); // #16161
- $peer_min->setRequired(true);
- $peer_min->setSize(3);
- $peer_min->setValue(2);
- $form->addItem($peer_min);
-
- $peer_unlock = new ilRadioGroupInputGUI($lng->txt("exc_peer_review_simple_unlock"), "peer_unlock");
- $peer_unlock->addOption(new ilRadioOption($lng->txt("exc_peer_review_simple_unlock_active"), 1));
- $peer_unlock->addOption(new ilRadioOption($lng->txt("exc_peer_review_simple_unlock_inactive"), 0));
- $peer_unlock->setRequired(true);
- $peer_unlock->setValue(0);
- $form->addItem($peer_unlock);
-
- if($this->enable_peer_review_completion)
- {
- $peer_cmpl = new ilRadioGroupInputGUI($lng->txt("exc_peer_review_completion"), "peer_valid");
- $option = new ilRadioOption($lng->txt("exc_peer_review_completion_none"), ilExAssignment::PEER_REVIEW_VALID_NONE);
- $option->setInfo($lng->txt("exc_peer_review_completion_none_info"));
- $peer_cmpl->addOption($option);
- $option = new ilRadioOption($lng->txt("exc_peer_review_completion_one"), ilExAssignment::PEER_REVIEW_VALID_ONE);
- $option->setInfo($lng->txt("exc_peer_review_completion_one_info"));
- $peer_cmpl->addOption($option);
- $option = new ilRadioOption($lng->txt("exc_peer_review_completion_all"), ilExAssignment::PEER_REVIEW_VALID_ALL);
- $option->setInfo($lng->txt("exc_peer_review_completion_all_info"));
- $peer_cmpl->addOption($option);
- $peer_cmpl->setRequired(true);
- $peer_cmpl->setValue(ilExAssignment::PEER_REVIEW_VALID_NONE);
- $form->addItem($peer_cmpl);
- }
-
- $peer_dl = new ilDateTimeInputGUI($lng->txt("exc_peer_review_deadline"), "peer_dl");
- $peer_dl->setInfo($lng->txt("exc_peer_review_deadline_info"));
- $peer_dl->setShowTime(true);
- $form->addItem($peer_dl);
-
- $peer_prsl = new ilCheckboxInputGUI($lng->txt("exc_peer_review_personal"), "peer_prsl");
- $peer_prsl->setInfo($lng->txt("exc_peer_review_personal_info"));
- $form->addItem($peer_prsl);
-
- //feedback reminders
- $rmd_feedback = new ilCheckboxInputGUI($this->lng->txt("exc_reminder_feedback_setting"), "rmd_peer_status");
-
- $rmd_submit_start = new ilNumberInputGUI($this->lng->txt("exc_reminder_feedback_start"), "rmd_peer_start");
- $rmd_submit_start->setSize(3);
- $rmd_submit_start->setMaxLength(3);
- $rmd_submit_start->setSuffix($lng->txt('days'));
- $rmd_submit_start->setRequired(true);
- $rmd_submit_start->setMinValue(1);
- $rmd_feedback->addSubItem($rmd_submit_start);
-
- $rmd_submit_frequency = new ilNumberInputGUI($this->lng->txt("exc_reminder_frequency"), "rmd_peer_freq");
- $rmd_submit_frequency->setSize(3);
- $rmd_submit_frequency->setMaxLength(3);
- $rmd_submit_frequency->setSuffix($lng->txt('days'));
- $rmd_submit_frequency->setRequired(true);
- $rmd_submit_frequency->setMinValue(1);
- $rmd_feedback->addSubItem($rmd_submit_frequency);
-
- $rmd_submit_end = new ilDateTimeInputGUI($lng->txt("exc_reminder_end"), "rmd_peer_end");
- $rmd_submit_end->setRequired(true);
- $rmd_feedback->addSubItem($rmd_submit_end);
-
- $rmd_feedback->addSubItem($this->addMailTemplatesRadio(ilExAssignmentReminder::FEEDBACK_REMINDER));
-
- $form->addItem($rmd_feedback);
-
- // criteria
-
- $cats = new ilRadioGroupInputGUI($lng->txt("exc_criteria_catalogues"), "crit_cat");
- $form->addItem($cats);
-
- // default (no catalogue)
-
- $def = new ilRadioOption($lng->txt("exc_criteria_catalogue_default"), -1);
- $cats->addOption($def);
-
- $peer_text = new ilCheckboxInputGUI($lng->txt("exc_peer_review_text"), "peer_text");
- $def->addSubItem($peer_text);
-
- $peer_char = new ilNumberInputGUI($lng->txt("exc_peer_review_min_chars"), "peer_char");
- $peer_char->setInfo($lng->txt("exc_peer_review_min_chars_info"));
- $peer_char->setSize(3);
- $peer_text->addSubItem($peer_char);
-
- $peer_rating = new ilCheckboxInputGUI($lng->txt("exc_peer_review_rating"), "peer_rating");
- $def->addSubItem($peer_rating);
-
- $peer_file = new ilCheckboxInputGUI($lng->txt("exc_peer_review_file"), "peer_file");
- $peer_file->setInfo($lng->txt("exc_peer_review_file_info"));
- $def->addSubItem($peer_file);
-
- // catalogues
-
- include_once "Modules/Exercise/classes/class.ilExcCriteriaCatalogue.php";
- $cat_objs = ilExcCriteriaCatalogue::getInstancesByParentId($this->exercise_id);
- if(sizeof($cat_objs))
- {
- include_once "Modules/Exercise/classes/class.ilExcCriteria.php";
- foreach($cat_objs as $cat_obj)
- {
- $crits = ilExcCriteria::getInstancesByParentId($cat_obj->getId());
-
- // only non-empty catalogues
- if(sizeof($crits))
- {
- $titles = array();
- foreach($crits as $crit)
- {
- $titles[] = $crit->getTitle();
- }
- $opt = new ilRadioOption($cat_obj->getTitle(), $cat_obj->getId());
- $opt->setInfo(implode(", ", $titles));
- $cats->addOption($opt);
- }
- }
- }
- else
- {
- // see ilExcCriteriaCatalogueGUI::view()
- $url = $ilCtrl->getLinkTargetByClass("ilexccriteriacataloguegui", "");
- $def->setInfo('[+] '.
- $lng->txt("exc_add_criteria_catalogue").
- '');
- }
-
-
- $form->addCommandButton("updatePeerReview", $lng->txt("save"));
- $form->addCommandButton("editAssignment", $lng->txt("cancel"));
-
- return $form;
- }
-
- public function editPeerReviewObject(ilPropertyFormGUI $a_form = null)
- {
- $tpl = $this->tpl;
- $ilTabs = $this->tabs;
- $tpl = $this->tpl;
-
- $this->setAssignmentHeader();
- $ilTabs->activateTab("peer_settings");
-
- if($a_form === null)
- {
- $a_form = $this->initPeerReviewForm();
- $this->getPeerReviewValues($a_form);
- }
- $tpl->setContent($a_form->getHTML());
- }
-
- protected function getPeerReviewValues($a_form)
- {
- $values = array();
-
- if($this->assignment->getPeerReviewDeadline() > 0)
- {
- $values["peer_dl"] = new ilDateTime($this->assignment->getPeerReviewDeadline(), IL_CAL_UNIX);
- }
-
- $this->assignment->getId();
- $this->exercise_id;
- $reminder = new ilExAssignmentReminder($this->exercise_id, $this->assignment->getId(), ilExAssignmentReminder::FEEDBACK_REMINDER);
- if($reminder->getReminderStatus())
- {
- $values["rmd_peer_status"] = $reminder->getReminderStatus();
- $values["rmd_peer_start"] = $reminder->getReminderStart();
- $values["rmd_peer_end"] = new ilDateTime($reminder->getReminderEnd(), IL_CAL_UNIX);
- $values["rmd_peer_freq"] = $reminder->getReminderFrequency();
- $values["rmd_peer_template_id"] = $reminder->getReminderMailTemplate();
- }
-
- $a_form->setValuesByArray($values);
-
- $this->handleDisabledPeerFields($a_form, true);
- }
-
- protected function setDisabledPeerReviewFieldValues(ilPropertyFormGUI $a_form)
- {
- $a_form->getItemByPostVar("peer_min")->setValue($this->assignment->getPeerReviewMin());
- $a_form->getItemByPostVar("peer_prsl")->setChecked($this->assignment->hasPeerReviewPersonalized());
- $a_form->getItemByPostVar("peer_unlock")->setValue((int)$this->assignment->getPeerReviewSimpleUnlock());
-
- if($this->enable_peer_review_completion)
- {
- $a_form->getItemByPostVar("peer_valid")->setValue($this->assignment->getPeerReviewValid());
- }
-
- $cat = $this->assignment->getPeerReviewCriteriaCatalogue();
- if($cat < 1)
- {
- $cat = -1;
-
- // default / no catalogue
- $a_form->getItemByPostVar("peer_text")->setChecked($this->assignment->hasPeerReviewText());
- $a_form->getItemByPostVar("peer_rating")->setChecked($this->assignment->hasPeerReviewRating());
- $a_form->getItemByPostVar("peer_file")->setChecked($this->assignment->hasPeerReviewFileUpload());
- if ($this->assignment->getPeerReviewChars() > 0)
- {
- $a_form->getItemByPostVar("peer_char")->setValue($this->assignment->getPeerReviewChars());
- }
- }
- $a_form->getItemByPostVar("crit_cat")->setValue($cat);
- }
-
- protected function handleDisabledPeerFields(ilPropertyFormGUI $a_form, $a_force_set_values = false)
- {
- // #14450
- include_once "Modules/Exercise/classes/class.ilExPeerReview.php";
- $peer_review = new ilExPeerReview($this->assignment);
- if($peer_review->hasPeerReviewGroups())
- {
- // JourFixe, 2015-05-11 - editable again
- // $a_form->getItemByPostVar("peer_dl")->setDisabled(true);
-
- $a_form->getItemByPostVar("peer_min")->setDisabled(true);
- $a_form->getItemByPostVar("peer_prsl")->setDisabled(true);
- $a_form->getItemByPostVar("peer_unlock")->setDisabled(true);
-
- if($this->enable_peer_review_completion)
- {
- $a_form->getItemByPostVar("peer_valid")->setDisabled(true);
- }
-
- $a_form->getItemByPostVar("crit_cat")->setDisabled(true);
- $a_form->getItemByPostVar("peer_text")->setDisabled(true);
- $a_form->getItemByPostVar("peer_char")->setDisabled(true);
- $a_form->getItemByPostVar("peer_rating")->setDisabled(true);
- $a_form->getItemByPostVar("peer_file")->setDisabled(true);
-
- // required number input is a problem
- $min = new ilHiddenInputGUI("peer_min");
- $min->setValue($this->assignment->getPeerReviewMin());
- $a_form->addItem($min);
- }
-
- if($a_force_set_values ||
- $peer_review->hasPeerReviewGroups())
- {
- $this->setDisabledPeerReviewFieldValues($a_form);
- }
- }
-
- protected function processPeerReviewForm(ilPropertyFormGUI $a_form)
- {
- $lng = $this->lng;
-
- $protected_peer_review_groups = false;
- include_once "Modules/Exercise/classes/class.ilExPeerReview.php";
- $peer_review = new ilExPeerReview($this->assignment);
- if($peer_review->hasPeerReviewGroups())
- {
- $protected_peer_review_groups = true;
- }
-
- $valid = $a_form->checkInput();
- if($valid)
- {
- // dates
- $time_deadline = $this->assignment->getDeadline();
- $time_deadline_ext = $this->assignment->getExtendedDeadline();
- $time_deadline_max = max($time_deadline, $time_deadline_ext);
-
- $date = $a_form->getItemByPostVar("peer_dl")->getDate();
- $time_peer = $date
- ? $date->get(IL_CAL_UNIX)
- : null;
-
- $reminder_date = $a_form->getItemByPostVar("rmd_peer_end")->getDate();
- $reminder_date = $reminder_date
- ? $reminder_date->get(IL_CAL_UNIX)
- : null;
-
- // peer < any deadline?
- if($time_peer && $time_deadline_max && $time_peer < $time_deadline_max)
- {
- $a_form->getItemByPostVar("peer_dl")
- ->setAlert($lng->txt("exc_peer_deadline_mismatch"));
- $valid = false;
- }
-
- if(!$protected_peer_review_groups)
- {
- if($a_form->getInput("crit_cat") < 0 &&
- !$a_form->getInput("peer_text") &&
- !$a_form->getInput("peer_rating") &&
- !$a_form->getInput("peer_file"))
- {
- $a_form->getItemByPostVar("peer_file")
- ->setAlert($lng->txt("select_one"));
- $valid = false;
- }
- }
-
- if($valid)
- {
- $res = array();
- $res["peer_dl"] = $time_peer;
-
- if($protected_peer_review_groups)
- {
- $res["peer_min"] = $this->assignment->getPeerReviewMin();
- $res["peer_unlock"] = $this->assignment->getPeerReviewSimpleUnlock();
- $res["peer_prsl"] = $this->assignment->hasPeerReviewPersonalized();
- $res["peer_valid"] = $this->assignment->getPeerReviewValid();
-
- $res["peer_text"] = $this->assignment->hasPeerReviewText();
- $res["peer_rating"] = $this->assignment->hasPeerReviewRating();
- $res["peer_file"] = $this->assignment->hasPeerReviewFileUpload();
- $res["peer_char"] = $this->assignment->getPeerReviewChars();
- $res["crit_cat"] = $this->assignment->getPeerReviewCriteriaCatalogue();
-
- $res["peer_valid"] = $this->enable_peer_review_completion
- ? $res["peer_valid"]
- : null;
- }
- else
- {
- $res["peer_min"] = $a_form->getInput("peer_min");
- $res["peer_unlock"] = $a_form->getInput("peer_unlock");
- $res["peer_prsl"] = $a_form->getInput("peer_prsl");
- $res["peer_valid"] = $a_form->getInput("peer_valid");
-
- $res["peer_text"] = $a_form->getInput("peer_text");
- $res["peer_rating"] = $a_form->getInput("peer_rating");
- $res["peer_file"] = $a_form->getInput("peer_file");
- $res["peer_char"] = $a_form->getInput("peer_char");
- $res["crit_cat"] = $a_form->getInput("crit_cat");
- }
- if($a_form->getInput("rmd_peer_status"))
- {
- $res["rmd_peer_status"] = $a_form->getInput("rmd_peer_status");
- $res["rmd_peer_start"] = $a_form->getInput("rmd_peer_start");
- $res["rmd_peer_end"] = $reminder_date;
- $res["rmd_peer_freq"] = $a_form->getInput("rmd_peer_freq");
- $res["rmd_peer_template_id"] = $a_form->getInput("rmd_peer_template_id");
- }
-
- return $res;
- }
- else
- {
- ilUtil::sendFailure($lng->txt("form_input_not_valid"));
- }
- }
- }
-
- protected function importPeerReviewFormToAssignment(ilExAssignment $a_ass, array $a_input)
- {
- $a_ass->setPeerReviewMin($a_input["peer_min"]);
- $a_ass->setPeerReviewDeadline($a_input["peer_dl"]);
- $a_ass->setPeerReviewSimpleUnlock($a_input["peer_unlock"]);
- $a_ass->setPeerReviewPersonalized($a_input["peer_prsl"]);
-
- // #18964
- $a_ass->setPeerReviewValid($a_input["peer_valid"]
- ? $a_input["peer_valid"]
- : ilExAssignment::PEER_REVIEW_VALID_NONE);
-
- $a_ass->setPeerReviewFileUpload($a_input["peer_file"]);
- $a_ass->setPeerReviewChars($a_input["peer_char"]);
- $a_ass->setPeerReviewText($a_input["peer_text"]);
- $a_ass->setPeerReviewRating($a_input["peer_rating"]);
- $a_ass->setPeerReviewCriteriaCatalogue($a_input["crit_cat"] > 0
- ? $a_input["crit_cat"]
- : null);
-
- $a_ass->update();
-
- $this->importPeerReviewFormToAssignmentReminders($a_input, $a_ass->getId());
- }
-
- protected function updatePeerReviewObject()
- {
- $tpl = $this->tpl;
- $lng = $this->lng;
- $ilCtrl = $this->ctrl;
- $ilTabs = $this->tabs;
-
- $form = $this->initPeerReviewForm();
- $input = $this->processPeerReviewForm($form);
- if(is_array($input))
- {
- $this->importPeerReviewFormToAssignment($this->assignment, $input);
- ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true);
- $ilCtrl->redirect($this, "editPeerReview");
- }
- else
- {
- $this->setAssignmentHeader();
- $ilTabs->activateTab("peer_settings");
-
- $form->setValuesByPost();
- $this->handleDisabledPeerFields($form);
- $tpl->setContent($form->getHtml());
- }
- }
-
-
- //
- // TEAM
- //
-
- /**
- * @param $a_num_teams integer
- * @param $a_min_participants integer
- * @param $a_max_participants integer
- * @return array
- */
- function validationTeamsFormation($a_num_teams, $a_min_participants, $a_max_participants)
- {
- $total_members = $this->getExerciseTotalMembers();
- $number_of_teams = $a_num_teams;
-
- if($number_of_teams){
- $members_per_team = round($total_members / $a_num_teams);
- } else {
- if($a_min_participants)
- {
- $number_of_teams = round($total_members / $a_min_participants);
- $participants_extra_team = $total_members % $a_min_participants;
- if($participants_extra_team > $number_of_teams)
- {
- //Can't create teams with this minimum of participants.
- $message = sprintf($this->lng->txt("exc_team_minimal_too_big"),$a_min_participants);
- return array("status" => "error", "msg" => $message, "field" => "min_participants_team");
- }
- }
- $members_per_team = 0;
- }
-
- if($a_min_participants > $a_max_participants)
- {
- $message = $this->lng->txt("exc_team_min_big_than_max");
- return array("status" => "error", "msg" => $message, "field" => "max_participants_team");
- }
-
- if( $a_max_participants > 0 && $members_per_team > $a_max_participants)
- {
- $message = sprintf($this->lng->txt("exc_team_max_small_than_members"),$a_max_participants, $members_per_team);
- return array("status" => "error", "msg" => $message, "field" => "max_participants_team");
- }
-
- if($members_per_team > 0 && $members_per_team < $a_min_participants)
- {
- $message = sprintf($this->lng->txt("exc_team_min_small_than_members"),$a_min_participants, $members_per_team);
- return array("status" => "error", "msg" => $message, "field" => "min_participants_team");
- }
-
- return array("status" => "success", "msg" => "");
- }
-
- /**
- * Get the total number of exercise members
- * @return int
- */
- function getExerciseTotalMembers()
- {
- $exercise = new ilObjExercise($this->exercise_id, false);
- $exc_members = new ilExerciseMembers($exercise);
-
- return count($exc_members->getMembers());
- }
-
- /**
- * @param ilExAssignment $a_assignment
- * @param array $a_input
- */
- function generateTeams(ilExAssignment $a_assignment, $a_input)
- {
- $ass_type = $a_assignment->getAssignmentType();
- if ($ass_type->usesTeams() &&
- $a_input['team_creator'] == ilExAssignment::TEAMS_FORMED_BY_TUTOR)
- {
- if($a_input['team_creation'] == ilExAssignment::TEAMS_FORMED_BY_RANDOM)
- {
- $number_teams = $a_input['number_teams'];
- if(count(ilExAssignmentTeam::getAssignmentTeamMap($a_assignment->getId())) == 0)
- {
- $ass_team = new ilExAssignmentTeam();
- $ass_team->createRandomTeams($this->exercise_id, $a_assignment->getId(), $number_teams, $a_input['min_participants_team']);
- }
- }
- elseif ($a_input['team_creation'] == ilExAssignment::TEAMS_FORMED_BY_ASSIGNMENT)
- {
- ilExAssignmentTeam::adoptTeams($a_input["ass_adpt"], $a_assignment->getId());
- ilUtil::sendInfo($this->lng->txt("exc_teams_assignment_adopted"), true);
- }
- }
-
- }
+ } elseif ($a_input['team_creation'] == ilExAssignment::TEAMS_FORMED_BY_ASSIGNMENT) {
+ ilExAssignmentTeam::adoptTeams($a_input["ass_adpt"], $a_assignment->getId());
+ ilUtil::sendInfo($this->lng->txt("exc_teams_assignment_adopted"), true);
+ }
+ }
+ }
}
diff --git a/Modules/Exercise/classes/class.ilExAssignmentFileSystemGUI.php b/Modules/Exercise/classes/class.ilExAssignmentFileSystemGUI.php
index bcc67a5dbf06336fedbfa88dbabdd45f45fdc108..048f8c80db8a9effbcc9baf6da434af3fbd621f5 100644
--- a/Modules/Exercise/classes/class.ilExAssignmentFileSystemGUI.php
+++ b/Modules/Exercise/classes/class.ilExAssignmentFileSystemGUI.php
@@ -12,90 +12,91 @@ include_once('./Services/FileSystem/classes/class.ilFileSystemGUI.php');
*/
class ilExAssignmentFileSystemGUI extends ilFileSystemGUI
{
-
- function __construct($a_main_directory)
- {
- global $DIC;
-
- $this->ctrl = $DIC->ctrl();
- parent::__construct($a_main_directory);
-
- }
-
- /**
- * Get table
- *
- * @param
- * @return
- */
- function getTable($a_dir, $a_subdir)
- {
- include_once("./Modules/Exercise/classes/class.ilExAssignmentFileSystemTableGUI.php");
- return new ilExAssignmentFileSystemTableGUI($this, "listFiles", $a_dir, $a_subdir,
- $this->label_enable, $this->file_labels, $this->label_header, $this->commands,
- $this->getPostDirPath(), $this->getTableId());
- }
-
-
- /**
- * Insert into database the file order and update the file.
- *
- * @param string view to redirect
- */
- public function uploadFile()
- {
- $filename = ilUtil::stripSlashes($_FILES["new_file"]["name"]);
-
- ilExAssignment::instructionFileInsertOrder($filename, $_GET['ass_id']);
- parent::uploadFile();
-
- }
-
- /**
- * Save all the orders.
- */
- public function saveFilesOrder()
- {
- $ilCtrl = $this->ctrl;
-
- if($_GET["ass_id"])
- {
- ilExAssignment::saveInstructionFilesOrderOfAssignment($_GET['ass_id'], $_POST["order"]);
- $ilCtrl->redirect($this, "listFiles");
- }
- }
-
- /**
- * delete object file
- * we can pass one parameter to deleteFile in fileSystemGUI, that contains the name of the class to redirect.
- * @param string view to redirect
- */
- function deleteFile()
- {
- if($_GET["ass_id"])
- {
- ilExAssignment::instructionFileDeleteOrder($_GET['ass_id'], $_POST["file"]);
-
- parent::deleteFile();
- }
- }
-
- /**
- * Rename File name
- */
- function renameFile()
- {
- if($_GET["ass_id"])
- {
- $new_name = str_replace("..", "", ilUtil::stripSlashes($_POST["new_name"]));
- $old_name = str_replace("/", "", $_GET["old_name"]);
-
- if($new_name != $old_name)
- {
- ilExAssignment::renameInstructionFile($old_name, $new_name, $_GET['ass_id']);
- }
- }
- parent::renameFile();
- }
-
-}
\ No newline at end of file
+ public function __construct($a_main_directory)
+ {
+ global $DIC;
+
+ $this->ctrl = $DIC->ctrl();
+ parent::__construct($a_main_directory);
+ }
+
+ /**
+ * Get table
+ *
+ * @param
+ * @return
+ */
+ public function getTable($a_dir, $a_subdir)
+ {
+ include_once("./Modules/Exercise/classes/class.ilExAssignmentFileSystemTableGUI.php");
+ return new ilExAssignmentFileSystemTableGUI(
+ $this,
+ "listFiles",
+ $a_dir,
+ $a_subdir,
+ $this->label_enable,
+ $this->file_labels,
+ $this->label_header,
+ $this->commands,
+ $this->getPostDirPath(),
+ $this->getTableId()
+ );
+ }
+
+
+ /**
+ * Insert into database the file order and update the file.
+ *
+ * @param string view to redirect
+ */
+ public function uploadFile()
+ {
+ $filename = ilUtil::stripSlashes($_FILES["new_file"]["name"]);
+
+ ilExAssignment::instructionFileInsertOrder($filename, $_GET['ass_id']);
+ parent::uploadFile();
+ }
+
+ /**
+ * Save all the orders.
+ */
+ public function saveFilesOrder()
+ {
+ $ilCtrl = $this->ctrl;
+
+ if ($_GET["ass_id"]) {
+ ilExAssignment::saveInstructionFilesOrderOfAssignment($_GET['ass_id'], $_POST["order"]);
+ $ilCtrl->redirect($this, "listFiles");
+ }
+ }
+
+ /**
+ * delete object file
+ * we can pass one parameter to deleteFile in fileSystemGUI, that contains the name of the class to redirect.
+ * @param string view to redirect
+ */
+ public function deleteFile()
+ {
+ if ($_GET["ass_id"]) {
+ ilExAssignment::instructionFileDeleteOrder($_GET['ass_id'], $_POST["file"]);
+
+ parent::deleteFile();
+ }
+ }
+
+ /**
+ * Rename File name
+ */
+ public function renameFile()
+ {
+ if ($_GET["ass_id"]) {
+ $new_name = str_replace("..", "", ilUtil::stripSlashes($_POST["new_name"]));
+ $old_name = str_replace("/", "", $_GET["old_name"]);
+
+ if ($new_name != $old_name) {
+ ilExAssignment::renameInstructionFile($old_name, $new_name, $_GET['ass_id']);
+ }
+ }
+ parent::renameFile();
+ }
+}
diff --git a/Modules/Exercise/classes/class.ilExAssignmentFileSystemTableGUI.php b/Modules/Exercise/classes/class.ilExAssignmentFileSystemTableGUI.php
index 61125c620e7e8cb6759aa88e5a23ab2206267601..2c4398a2edad48cae588580045b4e351115d7ecb 100644
--- a/Modules/Exercise/classes/class.ilExAssignmentFileSystemTableGUI.php
+++ b/Modules/Exercise/classes/class.ilExAssignmentFileSystemTableGUI.php
@@ -12,108 +12,116 @@ include_once('./Services/FileSystem/classes/class.ilFileSystemTableGUI.php');
*/
class ilExAssignmentFileSystemTableGUI extends ilFileSystemTableGUI
{
- //this property will define if the table needs order column.
- protected $add_order_column = true;
- protected $child_class_name = 'ilExAssignmentFileSystemTableGUI';
-
- function __construct($a_parent_obj, $a_parent_cmd, $a_cur_dir,
- $a_cur_subdir, $a_label_enable = false,
- $a_file_labels, $a_label_header = "", $a_commands = array(),
- $a_post_dir_path = false, $a_table_id = "")
- {
- global $DIC;
-
- $this->lng = $DIC->language();
-
- parent::__construct($a_parent_obj, $a_parent_cmd, $a_cur_dir,
- $a_cur_subdir, $a_label_enable,
- $a_file_labels, $a_label_header, $a_commands,
- $a_post_dir_path, "exc_instr_files");
-
- $this->setLimit(9999);
-
- //default template with order block
- //$this->setRowTemplate("tpl.exc_ass_instruction_file_row.html", "Modules/Exercise");
- $this->setDefaultOrderField("order_val");
- $this->setDefaultOrderDirection("asc");
- }
-
- /**
- * Add Order Values (extension of ilFilesystemgui getEntries)
- * @param array $a_entries
- * @return array items
- */
- function getEntries()
- {
- $entries = parent::getEntries();
- if(count($entries) > 0)
- {
- $this->addCommandButton("saveFilesOrder", $this->lng->txt("exc_save_order"));
- }
- $ass = new ilExAssignment((int) $_GET['ass_id']);
- return $ass->fileAddOrder($entries);
- }
-
- /**
- *
- *
- * @param
- * @return
- */
- function numericOrdering($a_field)
- {
- if ($a_field == "order_val")
- {
- return true;
- }
- return false;
- }
-
-
-
- public function addColumns()
- {
-
- if ($this->has_multi) {
- $this->setSelectAllCheckbox("file[]");
- $this->addColumn("", "", "1", true);
- }
-
- $this->addColumn($this->lng->txt("exc_presentation_order"), "order_val", "", false, $this->child_class_name);
-
- $this->addColumn("", "", "1", true); // icon
-
- $this->addColumn($this->lng->txt("cont_dir_file"), "name");
- $this->addColumn($this->lng->txt("cont_size"), "size");
-
- if ($this->label_enable) {
- $this->addColumn($this->label_header, "label");
- }
-
- if (sizeof($this->row_commands)) {
- $this->addColumn($this->lng->txt("actions"));
- include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php";
- }
- }
-
- /**
- * Fill table row
- */
- protected function fillRow($a_set)
- {
- $this->tpl->setCurrentBlock("Order");
- if($a_set['order_id'])
- {
- $this->tpl->setVariable("ID", $a_set['order_id']);
- }
- if($a_set["order_val"])
- {
- $this->tpl->setVariable("ORDER_VAL", $a_set["order_val"]);
-
- }
- $this->tpl->parseCurrentBlock();
-
- parent::fillRow($a_set);
- }
-
-}
\ No newline at end of file
+ //this property will define if the table needs order column.
+ protected $add_order_column = true;
+ protected $child_class_name = 'ilExAssignmentFileSystemTableGUI';
+
+ public function __construct(
+ $a_parent_obj,
+ $a_parent_cmd,
+ $a_cur_dir,
+ $a_cur_subdir,
+ $a_label_enable = false,
+ $a_file_labels,
+ $a_label_header = "",
+ $a_commands = array(),
+ $a_post_dir_path = false,
+ $a_table_id = ""
+ ) {
+ global $DIC;
+
+ $this->lng = $DIC->language();
+
+ parent::__construct(
+ $a_parent_obj,
+ $a_parent_cmd,
+ $a_cur_dir,
+ $a_cur_subdir,
+ $a_label_enable,
+ $a_file_labels,
+ $a_label_header,
+ $a_commands,
+ $a_post_dir_path,
+ "exc_instr_files"
+ );
+
+ $this->setLimit(9999);
+
+ //default template with order block
+ //$this->setRowTemplate("tpl.exc_ass_instruction_file_row.html", "Modules/Exercise");
+ $this->setDefaultOrderField("order_val");
+ $this->setDefaultOrderDirection("asc");
+ }
+
+ /**
+ * Add Order Values (extension of ilFilesystemgui getEntries)
+ * @param array $a_entries
+ * @return array items
+ */
+ public function getEntries()
+ {
+ $entries = parent::getEntries();
+ if (count($entries) > 0) {
+ $this->addCommandButton("saveFilesOrder", $this->lng->txt("exc_save_order"));
+ }
+ $ass = new ilExAssignment((int) $_GET['ass_id']);
+ return $ass->fileAddOrder($entries);
+ }
+
+ /**
+ *
+ *
+ * @param
+ * @return
+ */
+ public function numericOrdering($a_field)
+ {
+ if ($a_field == "order_val") {
+ return true;
+ }
+ return false;
+ }
+
+
+
+ public function addColumns()
+ {
+ if ($this->has_multi) {
+ $this->setSelectAllCheckbox("file[]");
+ $this->addColumn("", "", "1", true);
+ }
+
+ $this->addColumn($this->lng->txt("exc_presentation_order"), "order_val", "", false, $this->child_class_name);
+
+ $this->addColumn("", "", "1", true); // icon
+
+ $this->addColumn($this->lng->txt("cont_dir_file"), "name");
+ $this->addColumn($this->lng->txt("cont_size"), "size");
+
+ if ($this->label_enable) {
+ $this->addColumn($this->label_header, "label");
+ }
+
+ if (sizeof($this->row_commands)) {
+ $this->addColumn($this->lng->txt("actions"));
+ include_once "Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php";
+ }
+ }
+
+ /**
+ * Fill table row
+ */
+ protected function fillRow($a_set)
+ {
+ $this->tpl->setCurrentBlock("Order");
+ if ($a_set['order_id']) {
+ $this->tpl->setVariable("ID", $a_set['order_id']);
+ }
+ if ($a_set["order_val"]) {
+ $this->tpl->setVariable("ORDER_VAL", $a_set["order_val"]);
+ }
+ $this->tpl->parseCurrentBlock();
+
+ parent::fillRow($a_set);
+ }
+}
diff --git a/Modules/Exercise/classes/class.ilExAssignmentGUI.php b/Modules/Exercise/classes/class.ilExAssignmentGUI.php
index 3835d98d00b0841a380003e5623d8675d85aa007..8b66704d22816db2cb8765f3ecdd97cffd22a6fe 100644
--- a/Modules/Exercise/classes/class.ilExAssignmentGUI.php
+++ b/Modules/Exercise/classes/class.ilExAssignmentGUI.php
@@ -2,7 +2,7 @@
/**
* GUI class for exercise assignments
- *
+ *
* This is not a real GUI class, could be moved to ilObjExerciseGUI
*
* @author Alex Killing
".sprintf($lng->txt("exc_late_submission_warning"), $late_dl);
- $late_dl = ''.$late_dl.'';
- }
-
- if ($state->getCommonDeadline()) // if we have a common deadline (target timestamp)
- {
- $until = $state->getCommonDeadlinePresentation();
-
- // add late info if no idl
- if ($late_dl &&
- $state->getOfficialDeadline() == $state->getCommonDeadline())
- {
- $until .= $late_dl;
- }
-
- $prop = $lng->txt("exc_edit_until");
- if ($state->exceededOfficialDeadline())
- {
- $prop = $lng->txt("exc_ended_on");
- }
-
- $a_info->addProperty($prop, $until);
- }
- else if ($state->getRelativeDeadline()) // if we only have a relative deadline (not started yet)
- {
- $but = "";
- if ($state->hasGenerallyStarted())
- {
- $ilCtrl->setParameterByClass("ilobjexercisegui", "ass_id", $a_ass->getId());
- $but = $this->ui->factory()->button()->primary($lng->txt("exc_start_assignment"), $ilCtrl->getLinkTargetByClass("ilobjexercisegui", "startAssignment"));
- $ilCtrl->setParameterByClass("ilobjexercisegui", "ass_id", $_GET["ass_id"]);
- $but = $this->ui->renderer()->render($but);
- }
- $a_info->addProperty($lng->txt("exc_rem_time_after_start"), $state->getRelativeDeadlinePresentation().
- " ".$but);
- }
-
- if ($state->getOfficialDeadline() > $state->getCommonDeadline())
- {
- $until = $state->getOfficialDeadlinePresentation();
-
- // add late info?
- if ($late_dl)
- {
- $until .= $late_dl;
- }
-
- $a_info->addProperty($lng->txt("exc_individual_deadline"), $until);
- }
-
- if ($state->hasSubmissionStarted())
- {
- $a_info->addProperty($lng->txt("exc_time_to_send"),
- "".$state->getRemainingTimePresentation()."");
- }
- }
-
- protected function addPublicSubmissions(ilInfoScreenGUI $a_info, ilExAssignment $a_ass)
- {
- $lng = $this->lng;
- $ilUser = $this->user;
-
-
- include_once("./Modules/Exercise/classes/class.ilExcAssMemberState.php");
- $state = ilExcAssMemberState::getInstanceByIds($a_ass->getId(), $ilUser->getId());
-
- // submissions are visible, even if other users may still have a larger individual deadline
- if ($state->hasSubmissionEnded())
- {
- $button = ilLinkButton::getInstance();
- $button->setCaption("exc_list_submission");
- $button->setUrl($this->getSubmissionLink("listPublicSubmissions"));
-
- $a_info->addProperty($lng->txt("exc_public_submission"), $button->render());
- }
- else
- {
- $a_info->addProperty($lng->txt("exc_public_submission"),
- $lng->txt("exc_msg_public_submission"));
- }
- }
-
- protected function addFiles(ilInfoScreenGUI $a_info, ilExAssignment $a_ass)
- {
- $lng = $this->lng;
- $ilCtrl = $this->ctrl;
-
- $files = $a_ass->getFiles();
-
- if (count($files) > 0)
- {
- $a_info->addSection($lng->txt("exc_files"));
-
- global $DIC;
-
- //file has -> name,fullpath,size,ctime
- include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php");
- include_once("./Services/MediaObjects/classes/class.ilMediaPlayerGUI.php");
- include_once "./Services/UIComponent/Modal/classes/class.ilModalGUI.php";
-
- $cnt = 0;
- foreach($files as $file)
- {
- $cnt++;
- // get mime type
- $mime = ilObjMediaObject::getMimeType($file['fullpath']);
-
- list($format,$type) = explode("/",$mime);
-
- $ui_factory = $DIC->ui()->factory();
- $ui_renderer = $DIC->ui()->renderer();
-
- if (in_array($mime, array("image/jpeg", "image/svg+xml", "image/gif", "image/png")))
- {
- $item_id = "il-ex-modal-img-".$a_ass->getId()."-".$cnt;
-
-
- $image = $ui_renderer->render($ui_factory->image()->responsive($file['fullpath'], $file['name']));
- $image_lens = ilUtil::getImagePath("enlarge.svg");
-
- $modal = ilModalGUI::getInstance();
- $modal->setId($item_id);
- $modal->setType(ilModalGUI::TYPE_LARGE);
- $modal->setBody($image);
- $modal->setHeading($file["name"]);
- $modal = $modal->getHTML();
-
- $img_tpl = new ilTemplate("tpl.image_file.html", true, true, "Modules/Exercise");
- $img_tpl->setCurrentBlock("image_content");
- $img_tpl->setVariable("MODAL", $modal);
- $img_tpl->setVariable("ITEM_ID", $item_id);
- $img_tpl->setVariable("IMAGE", $image);
- $img_tpl->setvariable("IMAGE_LENS", $image_lens);
- $img_tpl->parseCurrentBlock();
-
- $a_info->addProperty($file["name"], $img_tpl->get());
- }
- else if (in_array($mime, array("audio/mpeg", "audio/ogg", "video/mp4", "video/x-flv", "video/webm")))
- {
- $media_tpl = new ilTemplate("tpl.media_file.html", true, true, "Modules/Exercise");
- $mp = new ilMediaPlayerGUI();
- $mp->setFile($file['fullpath']);
- $media_tpl->setVariable("MEDIA", $mp->getMediaPlayerHtml());
-
- $but = $ui_factory->button()->shy($lng->txt("download"),
- $this->getSubmissionLink("downloadFile", array("file"=>urlencode($file["name"]))));
- $media_tpl->setVariable("DOWNLOAD_BUTTON", $ui_renderer->render($but));
- $a_info->addProperty($file["name"], $media_tpl->get());
- }
- else
- {
- $a_info->addProperty($file["name"], $lng->txt("download"), $this->getSubmissionLink("downloadFile", array("file"=>urlencode($file["name"]))));
- }
- }
-
- }
- }
-
- protected function addSubmission(ilInfoScreenGUI $a_info, ilExAssignment $a_ass)
- {
- $lng = $this->lng;
- $ilCtrl = $this->ctrl;
- $ilUser = $this->user;
-
- include_once("./Modules/Exercise/classes/class.ilExcAssMemberState.php");
- $state = ilExcAssMemberState::getInstanceByIds($a_ass->getId(), $ilUser->getId());
-
- $a_info->addSection($lng->txt("exc_your_submission"));
-
- include_once "Modules/Exercise/classes/class.ilExSubmission.php";
- $submission = new ilExSubmission($a_ass, $ilUser->getId());
-
- include_once "Modules/Exercise/classes/class.ilExSubmissionGUI.php";
- ilExSubmissionGUI::getOverviewContent($a_info, $submission,$this->exc);
-
- $last_sub = null;
- if($submission->hasSubmitted())
- {
- $last_sub = $submission->getLastSubmission();
- if($last_sub)
- {
- $last_sub = ilDatePresentation::formatDate(new ilDateTime($last_sub,IL_CAL_DATETIME));
- $a_info->addProperty($lng->txt("exc_last_submission"), $last_sub);
- }
- }
-
- if ($this->exc->getShowSubmissions())
- {
- $this->addPublicSubmissions($a_info, $a_ass);
- }
-
- include_once "Modules/Exercise/classes/class.ilExPeerReviewGUI.php";
- ilExPeerReviewGUI::getOverviewContent($a_info, $submission);
-
- // global feedback / sample solution
- if($a_ass->getFeedbackDate() == ilExAssignment::FEEDBACK_DATE_DEADLINE)
- {
- $show_global_feedback = ($state->hasSubmissionEndedForAllUsers() && $a_ass->getFeedbackFile());
- }
- //If it is not well configured...(e.g. show solution before deadline)
- //the user can get the solution before he summit it.
- //we can check in the elseif $submission->hasSubmitted()
- elseif($a_ass->getFeedbackDate() == ilExAssignment::FEEDBACK_DATE_CUSTOM)
- {
- $show_global_feedback = ($a_ass->afterCustomDate() && $a_ass->getFeedbackFile());
- }
- else
- {
- $show_global_feedback = ($last_sub && $a_ass->getFeedbackFile());
- }
-
- $this->addSubmissionFeedback($a_info, $a_ass, $submission->getFeedbackId(), $show_global_feedback);
-
- }
-
- protected function addSubmissionFeedback(ilInfoScreenGUI $a_info, ilExAssignment $a_ass, $a_feedback_id, $a_show_global_feedback)
- {
- $lng = $this->lng;
-
- include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php");
-
- $storage = new ilFSStorageExercise($a_ass->getExerciseId(), $a_ass->getId());
- $cnt_files = $storage->countFeedbackFiles($a_feedback_id);
-
- $lpcomment = $a_ass->getMemberStatus()->getComment();
- $mark = $a_ass->getMemberStatus()->getMark();
- $status = $a_ass->getMemberStatus()->getStatus();
-
- if ($lpcomment != "" ||
- $mark != "" ||
- $status != "notgraded" ||
- $cnt_files > 0 ||
- $a_show_global_feedback)
- {
- $a_info->addSection($lng->txt("exc_feedback_from_tutor"));
- if ($lpcomment != "")
- {
- $a_info->addProperty($lng->txt("exc_comment"),
- nl2br($lpcomment));
- }
- if ($mark != "")
- {
- $a_info->addProperty($lng->txt("exc_mark"),
- $mark);
- }
-
- if ($status == "")
- {
-// $a_info->addProperty($lng->txt("status"),
-// $lng->txt("message_no_delivered_files"));
- }
- else if ($status != "notgraded")
- {
- $img = '';
- $a_info->addProperty($lng->txt("status"),
- $img." ".$lng->txt("exc_".$status));
- }
-
- if ($cnt_files > 0)
- {
- $a_info->addSection($lng->txt("exc_fb_files").
- '');
-
- if($cnt_files > 0)
- {
- $files = $storage->getFeedbackFiles($a_feedback_id);
- foreach($files as $file)
- {
- $a_info->addProperty($file,
- $lng->txt("download"),
- $this->getSubmissionLink("downloadFeedbackFile", array("file"=>urlencode($file))));
- }
- }
- }
-
- // #15002 - global feedback
- if($a_show_global_feedback)
- {
- $a_info->addSection($lng->txt("exc_global_feedback_file"));
-
- $a_info->addProperty($a_ass->getFeedbackFile(),
- $lng->txt("download"),
- $this->getSubmissionLink("downloadGlobalFeedbackFile"));
- }
- }
- }
-
- /**
- * Get time string for deadline
- */
- function getTimeString($a_deadline)
- {
- $lng = $this->lng;
-
- if ($a_deadline == 0)
- {
- return $lng->txt("exc_submit_convenience_no_deadline");
- }
-
- if ($a_deadline - time() <= 0)
- {
- $time_str = $lng->txt("exc_time_over_short");
- }
- else
- {
- $time_str = ilUtil::period2String(new ilDateTime($a_deadline, IL_CAL_UNIX));
- }
-
- return $time_str;
- }
-
- protected function getSubmissionLink($a_cmd, array $a_params = null)
- {
- $ilCtrl = $this->ctrl;
-
- if(is_array($a_params))
- {
- foreach($a_params as $name => $value)
- {
- $ilCtrl->setParameterByClass("ilexsubmissiongui", $name, $value);
- }
- }
-
- $ilCtrl->setParameterByClass("ilexsubmissiongui", "ass_id", $this->current_ass_id);
- $url = $ilCtrl->getLinkTargetByClass("ilexsubmissiongui", $a_cmd);
- $ilCtrl->setParameterByClass("ilexsubmissiongui", "ass_id", "");
-
- if(is_array($a_params))
- {
- foreach($a_params as $name => $value)
- {
- $ilCtrl->setParameterByClass("ilexsubmissiongui", $name, "");
- }
- }
-
- return $url;
- }
+ /**
+ * @var ilLanguage
+ */
+ protected $lng;
+
+ /**
+ * @var ilObjUser
+ */
+ protected $user;
+
+ /**
+ * @var ilCtrl
+ */
+ protected $ctrl;
+
+ protected $exc; // [ilObjExercise]
+ protected $current_ass_id; // [int]
+
+ /**
+ * Constructor
+ */
+ public function __construct(ilObjExercise $a_exc)
+ {
+ global $DIC;
+
+ $this->lng = $DIC->language();
+ $this->user = $DIC->user();
+ $this->ctrl = $DIC->ctrl();
+ $this->ui = $DIC->ui();
+
+ $this->exc = $a_exc;
+ }
+
+ /**
+ * Get assignment header for overview
+ */
+ public function getOverviewHeader(ilExAssignment $a_ass)
+ {
+ $lng = $this->lng;
+ $ilUser = $this->user;
+
+ $lng->loadLanguageModule("exc");
+
+ include_once("./Modules/Exercise/classes/class.ilExcAssMemberState.php");
+ $state = ilExcAssMemberState::getInstanceByIds($a_ass->getId(), $ilUser->getId());
+
+ $tpl = new ilTemplate("tpl.assignment_head.html", true, true, "Modules/Exercise");
+
+ // we are completely ignoring the extended deadline here
+
+ $idl = $a_ass->getPersonalDeadline($ilUser->getId());
+
+ // :TODO: meaning of "ended on"
+ $dl = max($a_ass->getDeadline(), $idl);
+ // if ($dl &&
+ // $dl < time())
+ if ($state->exceededOfficialDeadline()) {
+ $tpl->setCurrentBlock("prop");
+ $tpl->setVariable("PROP", $lng->txt("exc_ended_on"));
+ $tpl->setVariable("PROP_VAL", $state->getCommonDeadlinePresentation());
+ $tpl->parseCurrentBlock();
+
+ // #14077 // this currently shows the feedback deadline during grace period
+ if ($state->getPeerReviewDeadline()) {
+ $tpl->setCurrentBlock("prop");
+ $tpl->setVariable("PROP", $lng->txt("exc_peer_review_deadline"));
+ $tpl->setVariable("PROP_VAL", $state->getPeerReviewDeadlinePresentation());
+ $tpl->parseCurrentBlock();
+ }
+ } elseif (!$state->hasGenerallyStarted()) {
+ if ($state->getRelativeDeadline()) {
+ $tpl->setCurrentBlock("prop");
+ $tpl->setVariable("PROP", $lng->txt("exc_earliest_start_time"));
+ $tpl->setVariable("PROP_VAL", $state->getGeneralStartPresentation());
+ $tpl->parseCurrentBlock();
+ } else {
+ $tpl->setCurrentBlock("prop");
+ $tpl->setVariable("PROP", $lng->txt("exc_starting_on"));
+ $tpl->setVariable("PROP_VAL", $state->getGeneralStartPresentation());
+ $tpl->parseCurrentBlock();
+ }
+ } else {
+ if ($state->getCommonDeadline() > 0) {
+ $tpl->setCurrentBlock("prop");
+ $tpl->setVariable("PROP", $lng->txt("exc_time_to_send"));
+ $tpl->setVariable("PROP_VAL", $state->getRemainingTimePresentation());
+ $tpl->parseCurrentBlock();
+
+ $tpl->setCurrentBlock("prop");
+ $tpl->setVariable("PROP", $lng->txt("exc_edit_until"));
+ $tpl->setVariable("PROP_VAL", $state->getCommonDeadlinePresentation());
+ $tpl->parseCurrentBlock();
+ } elseif ($state->getRelativeDeadline()) { // if we only have a relative deadline (not started yet)
+ $tpl->setCurrentBlock("prop");
+ $tpl->setVariable("PROP", $lng->txt("exc_rem_time_after_start"));
+ $tpl->setVariable("PROP_VAL", $state->getRelativeDeadlinePresentation());
+ $tpl->parseCurrentBlock();
+ }
+
+
+ if ($state->getIndividualDeadline() > 0) {
+ $tpl->setCurrentBlock("prop");
+ $tpl->setVariable("PROP", $lng->txt("exc_individual_deadline"));
+ $tpl->setVariable("PROP_VAL", $state->getIndividualDeadlinePresentation());
+ $tpl->parseCurrentBlock();
+ }
+ }
+
+ $mand = "";
+ if ($a_ass->getMandatory()) {
+ $mand = " (" . $lng->txt("exc_mandatory") . ")";
+ }
+ $tpl->setVariable("TITLE", $a_ass->getTitle() . $mand);
+
+ // status icon
+ $stat = $a_ass->getMemberStatus()->getStatus();
+ $pic = $a_ass->getMemberStatus()->getStatusIcon();
+ $tpl->setVariable("IMG_STATUS", ilUtil::getImagePath($pic));
+ $tpl->setVariable("ALT_STATUS", $lng->txt("exc_" . $stat));
+
+ return $tpl->get();
+ }
+
+ /**
+ * Get assignment body for overview
+ */
+ public function getOverviewBody(ilExAssignment $a_ass)
+ {
+ global $DIC;
+
+ $ilUser = $DIC->user();
+
+ $this->current_ass_id = $a_ass->getId();
+
+ $tpl = new ilTemplate("tpl.assignment_body.html", true, true, "Modules/Exercise");
+
+ include_once("./Modules/Exercise/classes/class.ilExcAssMemberState.php");
+ $state = ilExcAssMemberState::getInstanceByIds($a_ass->getId(), $ilUser->getId());
+
+ include_once("./Services/InfoScreen/classes/class.ilInfoScreenGUI.php");
+ include_once("./Services/UIComponent/Button/classes/class.ilLinkButton.php");
+
+ $info = new ilInfoScreenGUI(null);
+ $info->setTableClass("");
+
+ if ($state->areInstructionsVisible()) {
+ $this->addInstructions($info, $a_ass);
+ $this->addFiles($info, $a_ass);
+ }
+
+ $this->addSchedule($info, $a_ass);
+
+ if ($state->hasSubmissionStarted()) {
+ $this->addSubmission($info, $a_ass);
+ }
+
+ $tpl->setVariable("CONTENT", $info->getHTML());
+
+ return $tpl->get();
+ }
+
+
+ protected function addInstructions(ilInfoScreenGUI $a_info, ilExAssignment $a_ass)
+ {
+ $ilUser = $this->user;
+ $lng = $this->lng;
+
+ include_once("./Modules/Exercise/classes/class.ilExcAssMemberState.php");
+ $state = ilExcAssMemberState::getInstanceByIds($a_ass->getId(), $ilUser->getId());
+
+ if ($state->areInstructionsVisible()) {
+ $inst = $a_ass->getInstruction();
+ if (trim($inst)) {
+ $a_info->addSection($lng->txt("exc_instruction"));
+
+ $is_html = (strlen($inst) != strlen(strip_tags($inst)));
+ if (!$is_html) {
+ $inst = nl2br(ilUtil::makeClickable($inst, true));
+ }
+ $a_info->addProperty("", $inst);
+ }
+ }
+ }
+
+ protected function addSchedule(ilInfoScreenGUI $a_info, ilExAssignment $a_ass)
+ {
+ $lng = $this->lng;
+ $ilUser = $this->user;
+ $ilCtrl = $this->ctrl;
+
+ $idl = $a_ass->getPersonalDeadline($ilUser->getId());
+
+ include_once("./Modules/Exercise/classes/class.ilExcAssMemberState.php");
+ $state = ilExcAssMemberState::getInstanceByIds($a_ass->getId(), $ilUser->getId());
+
+ $a_info->addSection($lng->txt("exc_schedule"));
+ if ($state->getGeneralStart() > 0) {
+ if ($state->getRelativeDeadline()) {
+ $a_info->addProperty($lng->txt("exc_earliest_start_time"), $state->getGeneralStartPresentation());
+ } else {
+ $a_info->addProperty($lng->txt("exc_start_time"), $state->getGeneralStartPresentation());
+ }
+ }
+
+ // extended deadline info/warning
+ $late_dl = "";
+ //if ($idl &&
+ // $idl < time() &&
+ // $a_ass->beforeDeadline()) // ext dl is last deadline
+ if ($state->inLateSubmissionPhase()) {
+ // extended deadline date should not be presented anywhere
+ $late_dl = $state->getOfficialDeadlinePresentation();
+ $late_dl = "
" . sprintf($lng->txt("exc_late_submission_warning"), $late_dl);
+ $late_dl = '' . $late_dl . '';
+ }
+
+ if ($state->getCommonDeadline()) { // if we have a common deadline (target timestamp)
+ $until = $state->getCommonDeadlinePresentation();
+
+ // add late info if no idl
+ if ($late_dl &&
+ $state->getOfficialDeadline() == $state->getCommonDeadline()) {
+ $until .= $late_dl;
+ }
+
+ $prop = $lng->txt("exc_edit_until");
+ if ($state->exceededOfficialDeadline()) {
+ $prop = $lng->txt("exc_ended_on");
+ }
+
+ $a_info->addProperty($prop, $until);
+ } elseif ($state->getRelativeDeadline()) { // if we only have a relative deadline (not started yet)
+ $but = "";
+ if ($state->hasGenerallyStarted()) {
+ $ilCtrl->setParameterByClass("ilobjexercisegui", "ass_id", $a_ass->getId());
+ $but = $this->ui->factory()->button()->primary($lng->txt("exc_start_assignment"), $ilCtrl->getLinkTargetByClass("ilobjexercisegui", "startAssignment"));
+ $ilCtrl->setParameterByClass("ilobjexercisegui", "ass_id", $_GET["ass_id"]);
+ $but = $this->ui->renderer()->render($but);
+ }
+ $a_info->addProperty($lng->txt("exc_rem_time_after_start"), $state->getRelativeDeadlinePresentation() .
+ " " . $but);
+ }
+
+ if ($state->getOfficialDeadline() > $state->getCommonDeadline()) {
+ $until = $state->getOfficialDeadlinePresentation();
+
+ // add late info?
+ if ($late_dl) {
+ $until .= $late_dl;
+ }
+
+ $a_info->addProperty($lng->txt("exc_individual_deadline"), $until);
+ }
+
+ if ($state->hasSubmissionStarted()) {
+ $a_info->addProperty(
+ $lng->txt("exc_time_to_send"),
+ "" . $state->getRemainingTimePresentation() . ""
+ );
+ }
+ }
+
+ protected function addPublicSubmissions(ilInfoScreenGUI $a_info, ilExAssignment $a_ass)
+ {
+ $lng = $this->lng;
+ $ilUser = $this->user;
+
+
+ include_once("./Modules/Exercise/classes/class.ilExcAssMemberState.php");
+ $state = ilExcAssMemberState::getInstanceByIds($a_ass->getId(), $ilUser->getId());
+
+ // submissions are visible, even if other users may still have a larger individual deadline
+ if ($state->hasSubmissionEnded()) {
+ $button = ilLinkButton::getInstance();
+ $button->setCaption("exc_list_submission");
+ $button->setUrl($this->getSubmissionLink("listPublicSubmissions"));
+
+ $a_info->addProperty($lng->txt("exc_public_submission"), $button->render());
+ } else {
+ $a_info->addProperty(
+ $lng->txt("exc_public_submission"),
+ $lng->txt("exc_msg_public_submission")
+ );
+ }
+ }
+
+ protected function addFiles(ilInfoScreenGUI $a_info, ilExAssignment $a_ass)
+ {
+ $lng = $this->lng;
+ $ilCtrl = $this->ctrl;
+
+ $files = $a_ass->getFiles();
+
+ if (count($files) > 0) {
+ $a_info->addSection($lng->txt("exc_files"));
+
+ global $DIC;
+
+ //file has -> name,fullpath,size,ctime
+ include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php");
+ include_once("./Services/MediaObjects/classes/class.ilMediaPlayerGUI.php");
+ include_once "./Services/UIComponent/Modal/classes/class.ilModalGUI.php";
+
+ $cnt = 0;
+ foreach ($files as $file) {
+ $cnt++;
+ // get mime type
+ $mime = ilObjMediaObject::getMimeType($file['fullpath']);
+
+ list($format, $type) = explode("/", $mime);
+
+ $ui_factory = $DIC->ui()->factory();
+ $ui_renderer = $DIC->ui()->renderer();
+
+ if (in_array($mime, array("image/jpeg", "image/svg+xml", "image/gif", "image/png"))) {
+ $item_id = "il-ex-modal-img-" . $a_ass->getId() . "-" . $cnt;
+
+
+ $image = $ui_renderer->render($ui_factory->image()->responsive($file['fullpath'], $file['name']));
+ $image_lens = ilUtil::getImagePath("enlarge.svg");
+
+ $modal = ilModalGUI::getInstance();
+ $modal->setId($item_id);
+ $modal->setType(ilModalGUI::TYPE_LARGE);
+ $modal->setBody($image);
+ $modal->setHeading($file["name"]);
+ $modal = $modal->getHTML();
+
+ $img_tpl = new ilTemplate("tpl.image_file.html", true, true, "Modules/Exercise");
+ $img_tpl->setCurrentBlock("image_content");
+ $img_tpl->setVariable("MODAL", $modal);
+ $img_tpl->setVariable("ITEM_ID", $item_id);
+ $img_tpl->setVariable("IMAGE", $image);
+ $img_tpl->setvariable("IMAGE_LENS", $image_lens);
+ $img_tpl->parseCurrentBlock();
+
+ $a_info->addProperty($file["name"], $img_tpl->get());
+ } elseif (in_array($mime, array("audio/mpeg", "audio/ogg", "video/mp4", "video/x-flv", "video/webm"))) {
+ $media_tpl = new ilTemplate("tpl.media_file.html", true, true, "Modules/Exercise");
+ $mp = new ilMediaPlayerGUI();
+ $mp->setFile($file['fullpath']);
+ $media_tpl->setVariable("MEDIA", $mp->getMediaPlayerHtml());
+
+ $but = $ui_factory->button()->shy(
+ $lng->txt("download"),
+ $this->getSubmissionLink("downloadFile", array("file"=>urlencode($file["name"])))
+ );
+ $media_tpl->setVariable("DOWNLOAD_BUTTON", $ui_renderer->render($but));
+ $a_info->addProperty($file["name"], $media_tpl->get());
+ } else {
+ $a_info->addProperty($file["name"], $lng->txt("download"), $this->getSubmissionLink("downloadFile", array("file"=>urlencode($file["name"]))));
+ }
+ }
+ }
+ }
+
+ protected function addSubmission(ilInfoScreenGUI $a_info, ilExAssignment $a_ass)
+ {
+ $lng = $this->lng;
+ $ilCtrl = $this->ctrl;
+ $ilUser = $this->user;
+
+ include_once("./Modules/Exercise/classes/class.ilExcAssMemberState.php");
+ $state = ilExcAssMemberState::getInstanceByIds($a_ass->getId(), $ilUser->getId());
+
+ $a_info->addSection($lng->txt("exc_your_submission"));
+
+ include_once "Modules/Exercise/classes/class.ilExSubmission.php";
+ $submission = new ilExSubmission($a_ass, $ilUser->getId());
+
+ include_once "Modules/Exercise/classes/class.ilExSubmissionGUI.php";
+ ilExSubmissionGUI::getOverviewContent($a_info, $submission, $this->exc);
+
+ $last_sub = null;
+ if ($submission->hasSubmitted()) {
+ $last_sub = $submission->getLastSubmission();
+ if ($last_sub) {
+ $last_sub = ilDatePresentation::formatDate(new ilDateTime($last_sub, IL_CAL_DATETIME));
+ $a_info->addProperty($lng->txt("exc_last_submission"), $last_sub);
+ }
+ }
+
+ if ($this->exc->getShowSubmissions()) {
+ $this->addPublicSubmissions($a_info, $a_ass);
+ }
+
+ include_once "Modules/Exercise/classes/class.ilExPeerReviewGUI.php";
+ ilExPeerReviewGUI::getOverviewContent($a_info, $submission);
+
+ // global feedback / sample solution
+ if ($a_ass->getFeedbackDate() == ilExAssignment::FEEDBACK_DATE_DEADLINE) {
+ $show_global_feedback = ($state->hasSubmissionEndedForAllUsers() && $a_ass->getFeedbackFile());
+ }
+ //If it is not well configured...(e.g. show solution before deadline)
+ //the user can get the solution before he summit it.
+ //we can check in the elseif $submission->hasSubmitted()
+ elseif ($a_ass->getFeedbackDate() == ilExAssignment::FEEDBACK_DATE_CUSTOM) {
+ $show_global_feedback = ($a_ass->afterCustomDate() && $a_ass->getFeedbackFile());
+ } else {
+ $show_global_feedback = ($last_sub && $a_ass->getFeedbackFile());
+ }
+
+ $this->addSubmissionFeedback($a_info, $a_ass, $submission->getFeedbackId(), $show_global_feedback);
+ }
+
+ protected function addSubmissionFeedback(ilInfoScreenGUI $a_info, ilExAssignment $a_ass, $a_feedback_id, $a_show_global_feedback)
+ {
+ $lng = $this->lng;
+
+ include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php");
+
+ $storage = new ilFSStorageExercise($a_ass->getExerciseId(), $a_ass->getId());
+ $cnt_files = $storage->countFeedbackFiles($a_feedback_id);
+
+ $lpcomment = $a_ass->getMemberStatus()->getComment();
+ $mark = $a_ass->getMemberStatus()->getMark();
+ $status = $a_ass->getMemberStatus()->getStatus();
+
+ if ($lpcomment != "" ||
+ $mark != "" ||
+ $status != "notgraded" ||
+ $cnt_files > 0 ||
+ $a_show_global_feedback) {
+ $a_info->addSection($lng->txt("exc_feedback_from_tutor"));
+ if ($lpcomment != "") {
+ $a_info->addProperty(
+ $lng->txt("exc_comment"),
+ nl2br($lpcomment)
+ );
+ }
+ if ($mark != "") {
+ $a_info->addProperty(
+ $lng->txt("exc_mark"),
+ $mark
+ );
+ }
+
+ if ($status == "") {
+ // $a_info->addProperty($lng->txt("status"),
+// $lng->txt("message_no_delivered_files"));
+ } elseif ($status != "notgraded") {
+ $img = '';
+ $a_info->addProperty(
+ $lng->txt("status"),
+ $img . " " . $lng->txt("exc_" . $status)
+ );
+ }
+
+ if ($cnt_files > 0) {
+ $a_info->addSection($lng->txt("exc_fb_files") .
+ '');
+
+ if ($cnt_files > 0) {
+ $files = $storage->getFeedbackFiles($a_feedback_id);
+ foreach ($files as $file) {
+ $a_info->addProperty(
+ $file,
+ $lng->txt("download"),
+ $this->getSubmissionLink("downloadFeedbackFile", array("file"=>urlencode($file)))
+ );
+ }
+ }
+ }
+
+ // #15002 - global feedback
+ if ($a_show_global_feedback) {
+ $a_info->addSection($lng->txt("exc_global_feedback_file"));
+
+ $a_info->addProperty(
+ $a_ass->getFeedbackFile(),
+ $lng->txt("download"),
+ $this->getSubmissionLink("downloadGlobalFeedbackFile")
+ );
+ }
+ }
+ }
+
+ /**
+ * Get time string for deadline
+ */
+ public function getTimeString($a_deadline)
+ {
+ $lng = $this->lng;
+
+ if ($a_deadline == 0) {
+ return $lng->txt("exc_submit_convenience_no_deadline");
+ }
+
+ if ($a_deadline - time() <= 0) {
+ $time_str = $lng->txt("exc_time_over_short");
+ } else {
+ $time_str = ilUtil::period2String(new ilDateTime($a_deadline, IL_CAL_UNIX));
+ }
+
+ return $time_str;
+ }
+
+ protected function getSubmissionLink($a_cmd, array $a_params = null)
+ {
+ $ilCtrl = $this->ctrl;
+
+ if (is_array($a_params)) {
+ foreach ($a_params as $name => $value) {
+ $ilCtrl->setParameterByClass("ilexsubmissiongui", $name, $value);
+ }
+ }
+
+ $ilCtrl->setParameterByClass("ilexsubmissiongui", "ass_id", $this->current_ass_id);
+ $url = $ilCtrl->getLinkTargetByClass("ilexsubmissiongui", $a_cmd);
+ $ilCtrl->setParameterByClass("ilexsubmissiongui", "ass_id", "");
+
+ if (is_array($a_params)) {
+ foreach ($a_params as $name => $value) {
+ $ilCtrl->setParameterByClass("ilexsubmissiongui", $name, "");
+ }
+ }
+
+ return $url;
+ }
}
diff --git a/Modules/Exercise/classes/class.ilExAssignmentListTextTableGUI.php b/Modules/Exercise/classes/class.ilExAssignmentListTextTableGUI.php
index 91e2f499a24c77d835210f45c27dd7371bd24990..79e978bad8164082aa9a60e77a953db6b94d53e5 100644
--- a/Modules/Exercise/classes/class.ilExAssignmentListTextTableGUI.php
+++ b/Modules/Exercise/classes/class.ilExAssignmentListTextTableGUI.php
@@ -1,169 +1,157 @@
-
-* @version $Id$
-*
-* @ingroup ModulesExercise
-*/
-class ilExAssignmentListTextTableGUI extends ilTable2GUI
-{
- protected $ass; // [ilExAssignment]
- protected $show_peer_review; // [bool]
- protected $peer_review; // [ilExPeerReview]
-
- function __construct($a_parent_obj, $a_parent_cmd, ilExAssignment $a_ass, $a_show_peer_review = false, $a_disable_peer_review = false)
- {
- global $DIC;
-
- $this->ctrl = $DIC->ctrl();
- $this->lng = $DIC->language();
- $ilCtrl = $DIC->ctrl();
- $lng = $DIC->language();
-
- $this->ass = $a_ass;
- $this->show_peer_review = (bool)$a_show_peer_review;
- $this->setId("excassltxt".$this->ass->getId());
-
- parent::__construct($a_parent_obj, $a_parent_cmd);
-
- $this->setTitle($lng->txt("exc_list_text_assignment").
- ": \"".$this->ass->getTitle()."\"");
-
- // if you add pagination and disable the unlimited setting:
- // fix saving of ordering of single pages!
- $this->setLimit(9999);
-
- $this->addColumn($this->lng->txt("user"), "uname", "15%");
- $this->addColumn($this->lng->txt("exc_last_submission"), "udate", "10%");
-
- if($this->show_peer_review)
- {
- $this->addColumn($this->lng->txt("exc_files_returned_text"), "", "45%");
- $this->addColumn($this->lng->txt("exc_peer_review"), "", "30%");
-
- include_once './Services/Rating/classes/class.ilRatingGUI.php';
- include_once './Services/Accordion/classes/class.ilAccordionGUI.php';
-
- $this->peer_review = new ilExPeerReview($this->ass);
- }
- else
- {
- $this->addColumn($this->lng->txt("exc_files_returned_text"), "", "75%");
- }
-
- $this->setDefaultOrderField("uname");
- $this->setDefaultOrderDirection("asc");
-
- $this->setFormAction($ilCtrl->getFormAction($a_parent_obj));
- $this->setRowTemplate("tpl.exc_list_text_assignment_row.html", "Modules/Exercise");
-
- if(!$a_disable_peer_review &&
- $this->ass->getPeerReview() &&
- !$a_show_peer_review)
- {
- $this->addCommandButton("listTextAssignment", $lng->txt("exc_show_peer_review"));
- }
-
- $this->parse();
- }
-
- public function numericOrdering($a_field)
- {
- return ($a_field == "udate");
- }
-
- protected function parse()
- {
- $peer_data = array();
- if($this->show_peer_review)
- {
- $peer_data = $this->peer_review->getAllPeerReviews();
- }
-
- include_once "Services/User/classes/class.ilUserUtil.php";
- include_once "Services/RTE/classes/class.ilRTE.php";
- foreach(ilExSubmission::getAllAssignmentFiles($this->ass->getExerciseId(), $this->ass->getId()) as $file)
- {
- if(trim($file["atext"]))
- {
- $data[$file["user_id"]] = array(
- "uid" => $file["user_id"],
- "uname" => ilUserUtil::getNamePresentation($file["user_id"]),
- "udate" => $file["ts"],
- "utext" => ilRTE::_replaceMediaObjectImageSrc($file["atext"], 1) // mob id to mob src
- );
-
- if(isset($peer_data[$file["user_id"]]))
- {
- $data[$file["user_id"]]["peer"] = array_keys($peer_data[$file["user_id"]]);
- }
- }
- }
-
- $this->setData($data);
- }
-
- protected function fillRow($a_set)
- {
- $ilCtrl = $this->ctrl;
-
- if($this->show_peer_review)
- {
- $peer_data = " ";
- if(isset($a_set["peer"]))
- {
- $acc = new ilAccordionGUI();
- $acc->setId($this->ass->getId()."_".$a_set["uid"]);
-
- foreach($a_set["peer"] as $peer_id)
- {
- $peer_name = ilUserUtil::getNamePresentation($peer_id);
- $acc_item = $peer_name;
-
- $submission = new ilExSubmission($this->ass, $a_set["uid"]);
- $values = $submission->getPeerReview()->getPeerReviewValues($peer_id, $a_set["uid"]);
-
- $acc_html = array();
- foreach($this->ass->getPeerReviewCriteriaCatalogueItems() as $crit)
- {
- $crit_id = $crit->getId()
- ? $crit->getId()
- : $crit->getType();
- $crit->setPeerReviewContext($this->ass, $peer_id, $a_set["uid"]);
-
- // see ilWikiAdvMetaDataBlockGUI
- $acc_html[] = '
' . + '
".$buttons_str."
"; - } - - - if($files_str) - { - $a_info->addProperty($lng->txt("exc_blog_returned"), $files_str); - } - if($a_submission->hasSubmitted()) - { - $ilCtrl->setParameterByClass("ilExSubmissionFileGUI", "delivered", $selected_blog["returned_id"]); - $dl_link = $ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionFileGUI"), "download"); - $ilCtrl->setParameterByClass("ilExSubmissionFileGUI", "delivered", ""); - - $button = ilLinkButton::getInstance(); - $button->setCaption("download"); - $button->setUrl($dl_link); - - $a_info->addProperty($lng->txt("exc_files_returned"), $button->render()); - } - } - - protected static function getOverviewContentPortfolio(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) - { - global $DIC; - - $lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - - include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; - - $files_str = ""; - $buttons_str = ""; - $valid_prtf = false; - $selected_prtf = $a_submission->getSelectedObject(); - if($selected_prtf) - { - $portfolio_id = (int)$selected_prtf["filetitle"]; - - // #11746 - if(ilObject::_exists($portfolio_id, false, "prtf")) - { - $portfolio = new ilObjPortfolio($portfolio_id, false); - if($portfolio->getTitle()) - { - // #10116 / #12791 - $ilCtrl->setParameterByClass("ilobjportfoliogui", "prt_id", $portfolio_id); - - $ref_id = $_REQUEST['ref_id']; - $ilCtrl->setParameterByClass("ilobjportfoliogui", "ref_id", $ref_id); - - $ilCtrl->setParameterByClass("ilobjportfoliogui", "exc_back_ref_id", (int) $_GET["ref_id"]); - - $prtf_link = $ilCtrl->getLinkTargetByClass(array("ilpersonaldesktopgui", "ilportfoliorepositorygui", "ilobjportfoliogui"), "view"); - $ilCtrl->setParameterByClass("ilobjportfoliogui", "prt_id", ""); - $ilCtrl->setParameterByClass("ilobjportfoliogui", "ref_id", ""); - - - $files_str = ''.$portfolio->getTitle().''; - $valid_prtf = true; - } - } - // remove invalid resource if no upload yet (see download below) - else if(substr($selected_prtf["filename"], -1) == "/") - { - // #16887 - $a_submission->deleteResourceObject($selected_prtf["returned_id"]); - } - } - if($a_submission->canSubmit()) - { - if(!$valid_prtf) - { - $button = ilLinkButton::getInstance(); - $button->setCaption("exc_create_portfolio"); - $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionObjectGUI"), "createPortfolioFromAssignment")); - - $buttons_str .= "".$button->render(); - } - // #10462 - //selectPortfolio ( remove it? ) - $prtfs = sizeof(ilObjPortfolio::getPortfoliosOfUser($a_submission->getUserId())); - if((!$valid_prtf && $prtfs) - || ($valid_prtf && $prtfs > 1)) - { - $button = ilLinkButton::getInstance(); - $button->setCaption("exc_select_portfolio".($valid_prtf ? "_change" : "")); - $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionObjectGUI"), "selectPortfolio")); - $buttons_str.= " ".$button->render(); - } - if($valid_prtf) - { - $button = ilLinkButton::getInstance(); - $button->setCaption("exc_select_portfolio".($valid_prtf ? "_unlink" : "")); - $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionObjectGUI"), "askUnlinkPortfolio")); - $buttons_str.= " ".$button->render(); - } - } - // todo: move this to ks somehow - if ($buttons_str != "") - { - $files_str.="".$buttons_str."
"; - } - if($files_str) - { - $a_info->addProperty($lng->txt("exc_portfolio_returned"), $files_str); - } - if($a_submission->hasSubmitted()) - { - $ilCtrl->setParameterByClass("ilExSubmissionFileGUI", "delivered", $selected_prtf["returned_id"]); - $dl_link =$ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionFileGUI"), "download"); - $ilCtrl->setParameterByClass("ilExSubmissionFileGUI", "delivered", ""); - - $button = ilLinkButton::getInstance(); - $button->setCaption("download"); - $button->setUrl($dl_link); - - $a_info->addProperty($lng->txt("exc_files_returned"), $button->render()); - } - } - - protected function renderResourceSelection($a_title, $a_info, $a_cmd, $a_explorer_cmd, array $a_items = null) - { - if(!$this->submission->canSubmit()) - { - ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); - $this->returnToParentObject(); - } - - $tpl = new ilTemplate("tpl.exc_select_resource.html", true, true, "Modules/Exercise"); - - if(is_array($a_items)) - { - $tpl->setCurrentBlock("item"); - foreach($a_items as $item_id => $item_title) - { - $tpl->setVariable("ITEM_ID", $item_id); - $tpl->setVariable("ITEM_TITLE", $item_title); - $tpl->parseCurrentBlock(); - } - $tpl->setVariable("FORM_ACTION", $this->ctrl->getFormAction($this)); - $tpl->setVariable("TXT_SUBMIT", $this->lng->txt("save")); - $tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); - $tpl->setVariable("CMD_SUBMIT", $a_cmd); - $tpl->setVariable("CMD_CANCEL", "returnToParent"); - $html = $tpl->get(); - } - else if($a_explorer_cmd) - { - $html = $this->renderWorkspaceExplorer($a_explorer_cmd); - } - - - ilUtil::sendInfo($this->lng->txt($a_info)); - - $title = $this->lng->txt($a_title).": ".$this->assignment->getTitle(); - - include_once "Services/UIComponent/Panel/classes/class.ilPanelGUI.php"; - $panel = ilPanelGUI::getInstance(); - $panel->setBody($html); - $panel->setHeading($title); - - $this->tpl->setContent($panel->getHTML()); - } - - - // - // BLOG - // - - protected function createBlogObject() - { - $this->handleTabs(); - - return $this->renderResourceSelection( - "exc_create_blog", - "exc_create_blog_select_info", - "saveBlog", - "createBlog" - ); - } - - protected function selectBlogObject() - { - $this->handleTabs(); - - return $this->renderResourceSelection( - "exc_select_blog", - "exc_select_blog_info", - "setSelectedBlog", - "selectBlog" - ); - } - - protected function saveBlogObject() - { - if (!$this->submission->canSubmit()) - { - ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); - $this->returnToParentObject(); - } - - if(!$_GET["sel_wsp_obj"]) - { - ilUtil::sendFailure($this->lng->txt("select_one")); - return $this->createBlogObject(); - } - - $parent_node = $_GET["sel_wsp_obj"]; - - include_once "Modules/Blog/classes/class.ilObjBlog.php"; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; - - $blog = new ilObjBlog(); - $blog->setTitle($this->exercise->getTitle()." - ".$this->assignment->getTitle()); - $blog->create(); - - $tree = new ilWorkspaceTree($this->submission->getUserId()); // #15993 - - $node_id = $tree->insertObject($parent_node, $blog->getId()); - - $access_handler = new ilWorkspaceAccessHandler($tree); - $access_handler->setPermissions($parent_node, $node_id); - - $this->submission->deleteAllFiles(); - $this->handleRemovedUpload(); - - $this->submission->addResourceObject($node_id); - - ilUtil::sendSuccess($this->lng->txt("exc_blog_created"), true); - $this->returnToParentObject(); - } - - protected function setSelectedBlogObject() - { - if (!$this->submission->canSubmit()) - { - ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); - $this->returnToParentObject(); - } - - if($_GET["sel_wsp_obj"]) - { - include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; - $tree = new ilWorkspaceTree($this->submission->getUserId()); - $node = $tree->getNodeData($_GET["sel_wsp_obj"]); - if($node && $node["type"] == "blog") - { - $this->submission->deleteAllFiles(); - $this->handleRemovedUpload(); - - $this->submission->addResourceObject($node["wsp_id"]); - - ilUtil::sendSuccess($this->lng->txt("exc_blog_selected"), true); - $this->ctrl->setParameter($this, "blog_id", $node["wsp_id"]); - $this->ctrl->redirect($this, "askDirectSubmission"); - } - } - -// ilUtil::sendFailure($this->lng->txt("select_one_blog")); - return $this->selectBlogObject(); - } - - /** - * @param string $a_cmd - * @return string - */ - protected function renderWorkspaceExplorer($a_cmd) - { - include_once("./Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php"); - switch ($a_cmd) - { - case "selectBlog": - $exp2 = new ilWorkspaceExplorerGUI($this->submission->getUserId(), $this, $a_cmd, $this, "setSelectedBlog"); - $exp2->setTypeWhiteList(array("blog", "wsrt", "wfld")); - $exp2->setSelectableTypes(array("blog")); - break; - - case "createBlog": - $exp2 = new ilWorkspaceExplorerGUI($this->submission->getUserId(), $this, $a_cmd, $this, "saveBlog"); - $exp2->setTypeWhiteList(array("wsrt", "wfld")); - $exp2->setSelectableTypes(array("wsrt", "wfld")); - break; - } - if (!$exp2->handleCommand()) - { - return $exp2->getHTML(); - } - exit; - } - - - // - // PORTFOLIO - // - - protected function selectPortfolioObject() - { - $this->handleTabs(); - - $items = array(); - include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; - $portfolios = ilObjPortfolio::getPortfoliosOfUser($this->submission->getUserId()); - if($portfolios) - { - foreach($portfolios as $portfolio) - { - $items[$portfolio["id"]]= $portfolio["title"]; - } - } - - return $this->renderResourceSelection( - "exc_select_portfolio", - "exc_select_portfolio_info", - "setSelectedPortfolio", - null, - $items - ); - } - - protected function initPortfolioTemplateForm(array $a_templates) - { - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setTitle($this->lng->txt("exc_create_portfolio").": ".$this->assignment->getTitle()); - $form->setFormAction($this->ctrl->getFormAction($this, "setSelectedPortfolioTemplate")); - - $prtt = new ilRadioGroupInputGUI($this->lng->txt("obj_prtt"), "prtt"); - $prtt->setRequired(true); - $prtt->addOption(new ilRadioOption($this->lng->txt("exc_create_portfolio_no_template"), -1)); - foreach($a_templates as $id => $title) - { - $prtt->addOption(new ilRadioOption('"'.$title.'"', $id)); - } - $prtt->setValue(-1); - $form->addItem($prtt); - - $form->addCommandButton("setSelectedPortfolioTemplate", $this->lng->txt("save")); - $form->addCommandButton("returnToParent", $this->lng->txt("cancel")); - - return $form; - } - - protected function createPortfolioFromAssignmentObject() - { - global $DIC; - - $ctrl = $DIC->ctrl(); - - include_once "Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"; - - $templates = ilObjPortfolioTemplate::getAvailablePortfolioTemplates(); - - //template id is stored in the DB with the ref_id. - $template_id = $this->assignment->getPortfolioTemplateId(); - //get the object id to compare with a list of template objects. - $template_object_id = ilObject::_lookupObjectId($template_id); - - // select a template, if available - if (count($templates) > 0 && $template_object_id == 0) - { - $this->createPortfolioTemplateObject(); - return; - } - - $title = $this->exercise->getTitle()." - ".$this->assignment->getTitle(); - $ctrl->setParameterByClass("ilObjPortfolioGUI", "exc_id", $this->exercise->getRefId()); - $ctrl->setParameterByClass("ilObjPortfolioGUI", "ass_id", $this->assignment->getId()); - $ctrl->setParameterByClass("ilObjPortfolioGUI", "pt", $title); - - if($template_object_id > 0) - { - $ctrl->setParameterByClass("ilObjPortfolioGUI", "prtt", $template_object_id); - } - $ctrl->setParameterByClass("ilobjportfoliogui", "exc_back_ref_id", (int) $_GET["ref_id"]); - $ctrl->redirectByClass(array("ilPersonalDesktopGUI", "ilPortfolioRepositoryGUI", "ilObjPortfolioGUI"), "createPortfolioFromAssignment"); - } - - protected function createPortfolioTemplateObject(ilPropertyFormGUI $a_form = null) - { - if (!$this->submission->canSubmit()) - { - ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); - $this->returnToParentObject(); - } - - include_once "Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"; - $templates = ilObjPortfolioTemplate::getAvailablePortfolioTemplates(); - if(!sizeof($templates)) - { - $this->returnToParentObject(); - } - - if(!$a_form) - { - $a_form = $this->initPortfolioTemplateForm($templates); - } - - $this->tpl->setContent($a_form->getHTML()); - } - - protected function setSelectedPortfolioTemplateObject() - { - if (!$this->submission->canSubmit()) - { - ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); - $this->returnToParentObject(); - } - - include_once "Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"; - $templates = ilObjPortfolioTemplate::getAvailablePortfolioTemplates(); - if(!sizeof($templates)) - { - $this->ctrl->redirect($this, "returnToParent"); - } - - $form = $this->initPortfolioTemplateForm($templates); - if($form->checkInput()) - { - $prtt = $form->getInput("prtt"); - if($prtt > 0 && array_key_exists($prtt, $templates)) - { - $title = $this->exercise->getTitle()." - ".$this->assignment->getTitle(); - $this->ctrl->setParameterByClass("ilObjPortfolioGUI", "exc_id", $this->exercise->getRefId()); - $this->ctrl->setParameterByClass("ilObjPortfolioGUI", "ass_id", $this->assignment->getId()); - $this->ctrl->setParameterByClass("ilObjPortfolioGUI", "pt", $title); - $this->ctrl->setParameterByClass("ilObjPortfolioGUI", "prtt", $prtt); - $this->ctrl->setParameterByClass("ilobjportfoliogui", "exc_back_ref_id", (int) $_GET["ref_id"]); - $this->ctrl->redirectByClass(array("ilPersonalDesktopGUI", "ilPortfolioRepositoryGUI", "ilObjPortfolioGUI"), "createPortfolioFromTemplate"); - } - else - { - // do not use template - return $this->createPortfolioObject(); - } - } - - $form->setValuesByPost(); - $this->createPortfolioTemplateObject($form); - } - - protected function createPortfolioObject() - { - if (!$this->submission->canSubmit()) - { - ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); - $this->returnToParentObject(); - } - - include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; - $portfolio = new ilObjPortfolio(); - $portfolio->setTitle($this->exercise->getTitle()." - ".$this->assignment->getTitle()); - $portfolio->create(); - - $this->submission->deleteAllFiles(); - $this->handleRemovedUpload(); - - $this->submission->addResourceObject($portfolio->getId()); - - ilUtil::sendSuccess($this->lng->txt("exc_portfolio_created"), true); - $this->returnToParentObject(); - } - - protected function setSelectedPortfolioObject() - { - if (!$this->submission->canSubmit()) - { - ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); - $this->returnToParentObject(); - } - - if($_POST["item"]) - { - $this->submission->deleteAllFiles(); - $this->handleRemovedUpload(); - - $this->submission->addResourceObject($_POST["item"]); - - ilUtil::sendSuccess($this->lng->txt("exc_portfolio_selected"), true); - $this->ctrl->setParameter($this, "prtf_id", $_POST["item"]); - $this->ctrl->redirect($this, "askDirectSubmission"); - } - - ilUtil::sendFailure($this->lng->txt("select_one")); - return $this->selectPortfolioObject(); - } - - protected function askUnlinkPortfolioObject() - { - $tpl = $this->tpl; - - include_once "Services/Utilities/classes/class.ilConfirmationGUI.php"; - $conf = new ilConfirmationGUI(); - $conf->setFormAction($this->ctrl->getFormAction($this, "unlinkPortfolio")); - $conf->setHeaderText($this->lng->txt("exc_sure_unlink_portfolio", "sure_unlink_portfolio")); - $conf->setConfirm($this->lng->txt("confirm"), "unlinkPortfolio"); - $conf->setCancel($this->lng->txt("cancel"), "returnToParent"); - - $submission = $this->submission->getSelectedObject(); - include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; - $port = new ilObjPortfolio($submission["filetitle"], false); - - $conf->addItem("id[]", "", $port->getTitle(), ilUtil::getImagePath("icon_prtf.svg")); - - $tpl->setContent($conf->getHTML()); - - } - - protected function unlinkPortfolioObject() - { - global $DIC; - - $user = $DIC->user(); - - $portfolio = $this->submission->getSelectedObject(); - $port_id = $portfolio["returned_id"]; - - $ilsub = new ilExSubmission($this->assignment, $user->getId()); - $ilsub->deleteResourceObject($port_id); - - ilUtil::sendSuccess($this->lng->txt("exc_portfolio_unlinked_from_assignment"), true); - - $this->ctrl->redirect($this, "returnToParent"); - } - - // - // SUBMIT BLOG/PORTFOLIO - // - - protected function askDirectSubmissionObject() - { - $tpl = $this->tpl; - - if (!$this->submission->canSubmit()) - { - ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); - $this->returnToParentObject(); - } - - include_once "Services/Utilities/classes/class.ilConfirmationGUI.php"; - $conf = new ilConfirmationGUI(); - - if($_REQUEST["blog_id"]) - { - $this->ctrl->setParameter($this, "blog_id", $_REQUEST["blog_id"]); - $txt = $this->lng->txt("exc_direct_submit_blog"); - } - else - { - $this->ctrl->setParameter($this, "prtf_id", $_REQUEST["prtf_id"]); - $txt = $this->lng->txt("exc_direct_submit_portfolio"); - } - $conf->setFormAction($this->ctrl->getFormAction($this, "directSubmit")); - - $conf->setHeaderText($txt); - $conf->setConfirm($this->lng->txt("exc_direct_submit"), "directSubmit"); - $conf->setCancel($this->lng->txt("exc_direct_no_submit"), "returnToParent"); - - $tpl->setContent($conf->getHTML()); - } - - protected function directSubmitObject() - { - if (!$this->submission->canSubmit()) - { - ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); - $this->returnToParentObject(); - } - - $success = false; - - // submit current version of blog - if($_REQUEST["blog_id"]) - { - $success = $this->submitBlog($_REQUEST["blog_id"]); - $this->ctrl->setParameter($this, "blog_id", ""); - } - // submit current version of portfolio - else if($_REQUEST["prtf_id"]) - { - $success = $this->submitPortfolio($_REQUEST["prtf_id"]); - $this->ctrl->setParameter($this, "prtf_id", ""); - } - - if($success) - { - ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); - } - else - { - ilUtil::sendFailure($this->lng->txt("msg_failed"), true); - } - $this->ctrl->redirect($this, "returnToParent"); - } - - /** - * Submit blog for assignment - * - * @param int $a_blog_id - * @return bool - */ - function submitBlog($a_blog_id) - { - if(!$this->submission->canSubmit()) - { - return; - } - - $blog_id = $a_blog_id; - - include_once "Modules/Blog/classes/class.ilObjBlogGUI.php"; - $blog_gui = new ilObjBlogGUI($blog_id, ilObjBlogGUI::WORKSPACE_NODE_ID); - if($blog_gui->object) - { - $file = $blog_gui->buildExportFile(); - $size = filesize($file); - if($size) - { - $this->submission->deleteAllFiles(); - - $meta = array( - "name" => $blog_id, - "tmp_name" => $file, - "size" => $size - ); - $this->submission->uploadFile($meta, true); - - $this->handleNewUpload(); - return true; - } - } - return false; - } - - /** - * Submit portfolio for assignment - * - * @param int $a_portfolio_id - * @return bool - */ - function submitPortfolio($a_portfolio_id) - { - if(!$this->submission->canSubmit()) - { - return; - } - - $prtf_id = $a_portfolio_id; - - include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; - $prtf = new ilObjPortfolio($prtf_id, false); - if($prtf->getTitle()) - { - include_once "Modules/Portfolio/classes/class.ilPortfolioHTMLExport.php"; - $export = new ilPortfolioHTMLExport(null, $prtf); - $file = $export->buildExportFile(); - $size = filesize($file); - if($size) - { - $this->submission->deleteAllFiles(); - - $meta = array( - "name" => $prtf_id, - "tmp_name" => $file, - "size" => $size - ); - $this->submission->uploadFile($meta, true); - - $this->handleNewUpload(); - return true; - } - } - return false; - } - - public static function initGUIForSubmit($a_ass_id, $a_user_id = null) - { - global $DIC; - - $ilUser = $DIC->user(); - - if(!$a_user_id) - { - $a_user_id = $ilUser->getId(); - } - - include_once "Modules/Exercise/classes/class.ilObjExercise.php"; - include_once "Modules/Exercise/classes/class.ilExAssignment.php"; - include_once "Modules/Exercise/classes/class.ilExSubmission.php"; - - $ass = new ilExAssignment($a_ass_id); - $sub = new ilExSubmission($ass, $a_user_id); - $exc_id = $ass->getExerciseId(); - - // #11173 - ref_id is needed for notifications - $exc_ref_id = array_shift(ilObject::_getAllReferences($exc_id)); - $exc = new ilObjExercise($exc_ref_id, true); - - return new self($exc, $sub); - } + /** + * Execute command + * + * @return mixed + * @throws ilCtrlException + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + if (!$this->submission->canView()) { + $this->returnToParentObject(); + } + + $class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd(); + + switch ($class) { + default: + $this->{$cmd . "Object"}(); + break; + } + } + + public static function getOverviewContent(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) + { + switch ($a_submission->getAssignment()->getType()) { + case ilExAssignment::TYPE_BLOG: + return self::getOverviewContentBlog($a_info, $a_submission); + + case ilExAssignment::TYPE_PORTFOLIO: + return self::getOverviewContentPortfolio($a_info, $a_submission); + } + } + + protected static function getOverviewContentBlog(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) + { + global $DIC; + + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $wsp_tree = new ilWorkspaceTree($a_submission->getUserId()); + + // #12939 + if (!$wsp_tree->getRootId()) { + $wsp_tree->createTreeForUser($a_submission->getUserId()); + } + + $files_str = ""; + $buttons_str = ""; + $valid_blog = false; + $selected_blog = $a_submission->getSelectedObject(); + if ($selected_blog) { + $blog_id = (int) $selected_blog["filetitle"]; + $node = $wsp_tree->getNodeData($blog_id); + if ($node["title"]) { + // #10116 + $ilCtrl->setParameterByClass("ilobjbloggui", "wsp_id", $blog_id); + $blog_link = $ilCtrl->getLinkTargetByClass(array("ilpersonaldesktopgui", "ilpersonalworkspacegui", "ilobjbloggui"), ""); + $ilCtrl->setParameterByClass("ilobjbloggui", "wsp_id", ""); + $files_str = '' . + $node["title"] . ''; + $valid_blog = true; + } + // remove invalid resource if no upload yet (see download below) + elseif (substr($selected_blog["filename"], -1) == "/") { + // #16887 + $a_submission->deleteResourceObject($selected_blog["returned_id"]); + } + } + if ($a_submission->canSubmit()) { + if (!$valid_blog) { + $button = ilLinkButton::getInstance(); + $button->setCaption("exc_create_blog"); + $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionObjectGUI"), "createBlog")); + $buttons_str.= $button->render(); + } + // #10462 + $blogs = sizeof($wsp_tree->getObjectsFromType("blog")); + if ((!$valid_blog && $blogs) + || ($valid_blog && $blogs > 1)) { + $button = ilLinkButton::getInstance(); + $button->setCaption("exc_select_blog" . ($valid_blog ? "_change" : "")); + $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionObjectGUI"), "selectBlog")); + $buttons_str.= " " . $button->render(); + } + } + + // todo: move this to ks somehow + if ($buttons_str != "") { + $files_str.="" . $buttons_str . "
"; + } + + + if ($files_str) { + $a_info->addProperty($lng->txt("exc_blog_returned"), $files_str); + } + if ($a_submission->hasSubmitted()) { + $ilCtrl->setParameterByClass("ilExSubmissionFileGUI", "delivered", $selected_blog["returned_id"]); + $dl_link = $ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionFileGUI"), "download"); + $ilCtrl->setParameterByClass("ilExSubmissionFileGUI", "delivered", ""); + + $button = ilLinkButton::getInstance(); + $button->setCaption("download"); + $button->setUrl($dl_link); + + $a_info->addProperty($lng->txt("exc_files_returned"), $button->render()); + } + } + + protected static function getOverviewContentPortfolio(ilInfoScreenGUI $a_info, ilExSubmission $a_submission) + { + global $DIC; + + $lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + + include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; + + $files_str = ""; + $buttons_str = ""; + $valid_prtf = false; + $selected_prtf = $a_submission->getSelectedObject(); + if ($selected_prtf) { + $portfolio_id = (int) $selected_prtf["filetitle"]; + + // #11746 + if (ilObject::_exists($portfolio_id, false, "prtf")) { + $portfolio = new ilObjPortfolio($portfolio_id, false); + if ($portfolio->getTitle()) { + // #10116 / #12791 + $ilCtrl->setParameterByClass("ilobjportfoliogui", "prt_id", $portfolio_id); + + $ref_id = $_REQUEST['ref_id']; + $ilCtrl->setParameterByClass("ilobjportfoliogui", "ref_id", $ref_id); + + $ilCtrl->setParameterByClass("ilobjportfoliogui", "exc_back_ref_id", (int) $_GET["ref_id"]); + + $prtf_link = $ilCtrl->getLinkTargetByClass(array("ilpersonaldesktopgui", "ilportfoliorepositorygui", "ilobjportfoliogui"), "view"); + $ilCtrl->setParameterByClass("ilobjportfoliogui", "prt_id", ""); + $ilCtrl->setParameterByClass("ilobjportfoliogui", "ref_id", ""); + + + $files_str = '' . $portfolio->getTitle() . ''; + $valid_prtf = true; + } + } + // remove invalid resource if no upload yet (see download below) + elseif (substr($selected_prtf["filename"], -1) == "/") { + // #16887 + $a_submission->deleteResourceObject($selected_prtf["returned_id"]); + } + } + if ($a_submission->canSubmit()) { + if (!$valid_prtf) { + $button = ilLinkButton::getInstance(); + $button->setCaption("exc_create_portfolio"); + $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionObjectGUI"), "createPortfolioFromAssignment")); + + $buttons_str .= "" . $button->render(); + } + // #10462 + //selectPortfolio ( remove it? ) + $prtfs = sizeof(ilObjPortfolio::getPortfoliosOfUser($a_submission->getUserId())); + if ((!$valid_prtf && $prtfs) + || ($valid_prtf && $prtfs > 1)) { + $button = ilLinkButton::getInstance(); + $button->setCaption("exc_select_portfolio" . ($valid_prtf ? "_change" : "")); + $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionObjectGUI"), "selectPortfolio")); + $buttons_str.= " " . $button->render(); + } + if ($valid_prtf) { + $button = ilLinkButton::getInstance(); + $button->setCaption("exc_select_portfolio" . ($valid_prtf ? "_unlink" : "")); + $button->setUrl($ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionObjectGUI"), "askUnlinkPortfolio")); + $buttons_str.= " " . $button->render(); + } + } + // todo: move this to ks somehow + if ($buttons_str != "") { + $files_str.="" . $buttons_str . "
"; + } + if ($files_str) { + $a_info->addProperty($lng->txt("exc_portfolio_returned"), $files_str); + } + if ($a_submission->hasSubmitted()) { + $ilCtrl->setParameterByClass("ilExSubmissionFileGUI", "delivered", $selected_prtf["returned_id"]); + $dl_link =$ilCtrl->getLinkTargetByClass(array("ilExSubmissionGUI", "ilExSubmissionFileGUI"), "download"); + $ilCtrl->setParameterByClass("ilExSubmissionFileGUI", "delivered", ""); + + $button = ilLinkButton::getInstance(); + $button->setCaption("download"); + $button->setUrl($dl_link); + + $a_info->addProperty($lng->txt("exc_files_returned"), $button->render()); + } + } + + protected function renderResourceSelection($a_title, $a_info, $a_cmd, $a_explorer_cmd, array $a_items = null) + { + if (!$this->submission->canSubmit()) { + ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); + $this->returnToParentObject(); + } + + $tpl = new ilTemplate("tpl.exc_select_resource.html", true, true, "Modules/Exercise"); + + if (is_array($a_items)) { + $tpl->setCurrentBlock("item"); + foreach ($a_items as $item_id => $item_title) { + $tpl->setVariable("ITEM_ID", $item_id); + $tpl->setVariable("ITEM_TITLE", $item_title); + $tpl->parseCurrentBlock(); + } + $tpl->setVariable("FORM_ACTION", $this->ctrl->getFormAction($this)); + $tpl->setVariable("TXT_SUBMIT", $this->lng->txt("save")); + $tpl->setVariable("TXT_CANCEL", $this->lng->txt("cancel")); + $tpl->setVariable("CMD_SUBMIT", $a_cmd); + $tpl->setVariable("CMD_CANCEL", "returnToParent"); + $html = $tpl->get(); + } elseif ($a_explorer_cmd) { + $html = $this->renderWorkspaceExplorer($a_explorer_cmd); + } + + + ilUtil::sendInfo($this->lng->txt($a_info)); + + $title = $this->lng->txt($a_title) . ": " . $this->assignment->getTitle(); + + include_once "Services/UIComponent/Panel/classes/class.ilPanelGUI.php"; + $panel = ilPanelGUI::getInstance(); + $panel->setBody($html); + $panel->setHeading($title); + + $this->tpl->setContent($panel->getHTML()); + } + + + // + // BLOG + // + + protected function createBlogObject() + { + $this->handleTabs(); + + return $this->renderResourceSelection( + "exc_create_blog", + "exc_create_blog_select_info", + "saveBlog", + "createBlog" + ); + } + + protected function selectBlogObject() + { + $this->handleTabs(); + + return $this->renderResourceSelection( + "exc_select_blog", + "exc_select_blog_info", + "setSelectedBlog", + "selectBlog" + ); + } + + protected function saveBlogObject() + { + if (!$this->submission->canSubmit()) { + ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); + $this->returnToParentObject(); + } + + if (!$_GET["sel_wsp_obj"]) { + ilUtil::sendFailure($this->lng->txt("select_one")); + return $this->createBlogObject(); + } + + $parent_node = $_GET["sel_wsp_obj"]; + + include_once "Modules/Blog/classes/class.ilObjBlog.php"; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceAccessHandler.php"; + + $blog = new ilObjBlog(); + $blog->setTitle($this->exercise->getTitle() . " - " . $this->assignment->getTitle()); + $blog->create(); + + $tree = new ilWorkspaceTree($this->submission->getUserId()); // #15993 + + $node_id = $tree->insertObject($parent_node, $blog->getId()); + + $access_handler = new ilWorkspaceAccessHandler($tree); + $access_handler->setPermissions($parent_node, $node_id); + + $this->submission->deleteAllFiles(); + $this->handleRemovedUpload(); + + $this->submission->addResourceObject($node_id); + + ilUtil::sendSuccess($this->lng->txt("exc_blog_created"), true); + $this->returnToParentObject(); + } + + protected function setSelectedBlogObject() + { + if (!$this->submission->canSubmit()) { + ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); + $this->returnToParentObject(); + } + + if ($_GET["sel_wsp_obj"]) { + include_once "Services/PersonalWorkspace/classes/class.ilWorkspaceTree.php"; + $tree = new ilWorkspaceTree($this->submission->getUserId()); + $node = $tree->getNodeData($_GET["sel_wsp_obj"]); + if ($node && $node["type"] == "blog") { + $this->submission->deleteAllFiles(); + $this->handleRemovedUpload(); + + $this->submission->addResourceObject($node["wsp_id"]); + + ilUtil::sendSuccess($this->lng->txt("exc_blog_selected"), true); + $this->ctrl->setParameter($this, "blog_id", $node["wsp_id"]); + $this->ctrl->redirect($this, "askDirectSubmission"); + } + } + + // ilUtil::sendFailure($this->lng->txt("select_one_blog")); + return $this->selectBlogObject(); + } + + /** + * @param string $a_cmd + * @return string + */ + protected function renderWorkspaceExplorer($a_cmd) + { + include_once("./Services/PersonalWorkspace/classes/class.ilWorkspaceExplorerGUI.php"); + switch ($a_cmd) { + case "selectBlog": + $exp2 = new ilWorkspaceExplorerGUI($this->submission->getUserId(), $this, $a_cmd, $this, "setSelectedBlog"); + $exp2->setTypeWhiteList(array("blog", "wsrt", "wfld")); + $exp2->setSelectableTypes(array("blog")); + break; + + case "createBlog": + $exp2 = new ilWorkspaceExplorerGUI($this->submission->getUserId(), $this, $a_cmd, $this, "saveBlog"); + $exp2->setTypeWhiteList(array("wsrt", "wfld")); + $exp2->setSelectableTypes(array("wsrt", "wfld")); + break; + } + if (!$exp2->handleCommand()) { + return $exp2->getHTML(); + } + exit; + } + + + // + // PORTFOLIO + // + + protected function selectPortfolioObject() + { + $this->handleTabs(); + + $items = array(); + include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; + $portfolios = ilObjPortfolio::getPortfoliosOfUser($this->submission->getUserId()); + if ($portfolios) { + foreach ($portfolios as $portfolio) { + $items[$portfolio["id"]]= $portfolio["title"]; + } + } + + return $this->renderResourceSelection( + "exc_select_portfolio", + "exc_select_portfolio_info", + "setSelectedPortfolio", + null, + $items + ); + } + + protected function initPortfolioTemplateForm(array $a_templates) + { + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setTitle($this->lng->txt("exc_create_portfolio") . ": " . $this->assignment->getTitle()); + $form->setFormAction($this->ctrl->getFormAction($this, "setSelectedPortfolioTemplate")); + + $prtt = new ilRadioGroupInputGUI($this->lng->txt("obj_prtt"), "prtt"); + $prtt->setRequired(true); + $prtt->addOption(new ilRadioOption($this->lng->txt("exc_create_portfolio_no_template"), -1)); + foreach ($a_templates as $id => $title) { + $prtt->addOption(new ilRadioOption('"' . $title . '"', $id)); + } + $prtt->setValue(-1); + $form->addItem($prtt); + + $form->addCommandButton("setSelectedPortfolioTemplate", $this->lng->txt("save")); + $form->addCommandButton("returnToParent", $this->lng->txt("cancel")); + + return $form; + } + + protected function createPortfolioFromAssignmentObject() + { + global $DIC; + + $ctrl = $DIC->ctrl(); + + include_once "Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"; + + $templates = ilObjPortfolioTemplate::getAvailablePortfolioTemplates(); + + //template id is stored in the DB with the ref_id. + $template_id = $this->assignment->getPortfolioTemplateId(); + //get the object id to compare with a list of template objects. + $template_object_id = ilObject::_lookupObjectId($template_id); + + // select a template, if available + if (count($templates) > 0 && $template_object_id == 0) { + $this->createPortfolioTemplateObject(); + return; + } + + $title = $this->exercise->getTitle() . " - " . $this->assignment->getTitle(); + $ctrl->setParameterByClass("ilObjPortfolioGUI", "exc_id", $this->exercise->getRefId()); + $ctrl->setParameterByClass("ilObjPortfolioGUI", "ass_id", $this->assignment->getId()); + $ctrl->setParameterByClass("ilObjPortfolioGUI", "pt", $title); + + if ($template_object_id > 0) { + $ctrl->setParameterByClass("ilObjPortfolioGUI", "prtt", $template_object_id); + } + $ctrl->setParameterByClass("ilobjportfoliogui", "exc_back_ref_id", (int) $_GET["ref_id"]); + $ctrl->redirectByClass(array("ilPersonalDesktopGUI", "ilPortfolioRepositoryGUI", "ilObjPortfolioGUI"), "createPortfolioFromAssignment"); + } + + protected function createPortfolioTemplateObject(ilPropertyFormGUI $a_form = null) + { + if (!$this->submission->canSubmit()) { + ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); + $this->returnToParentObject(); + } + + include_once "Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"; + $templates = ilObjPortfolioTemplate::getAvailablePortfolioTemplates(); + if (!sizeof($templates)) { + $this->returnToParentObject(); + } + + if (!$a_form) { + $a_form = $this->initPortfolioTemplateForm($templates); + } + + $this->tpl->setContent($a_form->getHTML()); + } + + protected function setSelectedPortfolioTemplateObject() + { + if (!$this->submission->canSubmit()) { + ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); + $this->returnToParentObject(); + } + + include_once "Modules/Portfolio/classes/class.ilObjPortfolioTemplate.php"; + $templates = ilObjPortfolioTemplate::getAvailablePortfolioTemplates(); + if (!sizeof($templates)) { + $this->ctrl->redirect($this, "returnToParent"); + } + + $form = $this->initPortfolioTemplateForm($templates); + if ($form->checkInput()) { + $prtt = $form->getInput("prtt"); + if ($prtt > 0 && array_key_exists($prtt, $templates)) { + $title = $this->exercise->getTitle() . " - " . $this->assignment->getTitle(); + $this->ctrl->setParameterByClass("ilObjPortfolioGUI", "exc_id", $this->exercise->getRefId()); + $this->ctrl->setParameterByClass("ilObjPortfolioGUI", "ass_id", $this->assignment->getId()); + $this->ctrl->setParameterByClass("ilObjPortfolioGUI", "pt", $title); + $this->ctrl->setParameterByClass("ilObjPortfolioGUI", "prtt", $prtt); + $this->ctrl->setParameterByClass("ilobjportfoliogui", "exc_back_ref_id", (int) $_GET["ref_id"]); + $this->ctrl->redirectByClass(array("ilPersonalDesktopGUI", "ilPortfolioRepositoryGUI", "ilObjPortfolioGUI"), "createPortfolioFromTemplate"); + } else { + // do not use template + return $this->createPortfolioObject(); + } + } + + $form->setValuesByPost(); + $this->createPortfolioTemplateObject($form); + } + + protected function createPortfolioObject() + { + if (!$this->submission->canSubmit()) { + ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); + $this->returnToParentObject(); + } + + include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; + $portfolio = new ilObjPortfolio(); + $portfolio->setTitle($this->exercise->getTitle() . " - " . $this->assignment->getTitle()); + $portfolio->create(); + + $this->submission->deleteAllFiles(); + $this->handleRemovedUpload(); + + $this->submission->addResourceObject($portfolio->getId()); + + ilUtil::sendSuccess($this->lng->txt("exc_portfolio_created"), true); + $this->returnToParentObject(); + } + + protected function setSelectedPortfolioObject() + { + if (!$this->submission->canSubmit()) { + ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); + $this->returnToParentObject(); + } + + if ($_POST["item"]) { + $this->submission->deleteAllFiles(); + $this->handleRemovedUpload(); + + $this->submission->addResourceObject($_POST["item"]); + + ilUtil::sendSuccess($this->lng->txt("exc_portfolio_selected"), true); + $this->ctrl->setParameter($this, "prtf_id", $_POST["item"]); + $this->ctrl->redirect($this, "askDirectSubmission"); + } + + ilUtil::sendFailure($this->lng->txt("select_one")); + return $this->selectPortfolioObject(); + } + + protected function askUnlinkPortfolioObject() + { + $tpl = $this->tpl; + + include_once "Services/Utilities/classes/class.ilConfirmationGUI.php"; + $conf = new ilConfirmationGUI(); + $conf->setFormAction($this->ctrl->getFormAction($this, "unlinkPortfolio")); + $conf->setHeaderText($this->lng->txt("exc_sure_unlink_portfolio", "sure_unlink_portfolio")); + $conf->setConfirm($this->lng->txt("confirm"), "unlinkPortfolio"); + $conf->setCancel($this->lng->txt("cancel"), "returnToParent"); + + $submission = $this->submission->getSelectedObject(); + include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; + $port = new ilObjPortfolio($submission["filetitle"], false); + + $conf->addItem("id[]", "", $port->getTitle(), ilUtil::getImagePath("icon_prtf.svg")); + + $tpl->setContent($conf->getHTML()); + } + + protected function unlinkPortfolioObject() + { + global $DIC; + + $user = $DIC->user(); + + $portfolio = $this->submission->getSelectedObject(); + $port_id = $portfolio["returned_id"]; + + $ilsub = new ilExSubmission($this->assignment, $user->getId()); + $ilsub->deleteResourceObject($port_id); + + ilUtil::sendSuccess($this->lng->txt("exc_portfolio_unlinked_from_assignment"), true); + + $this->ctrl->redirect($this, "returnToParent"); + } + + // + // SUBMIT BLOG/PORTFOLIO + // + + protected function askDirectSubmissionObject() + { + $tpl = $this->tpl; + + if (!$this->submission->canSubmit()) { + ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); + $this->returnToParentObject(); + } + + include_once "Services/Utilities/classes/class.ilConfirmationGUI.php"; + $conf = new ilConfirmationGUI(); + + if ($_REQUEST["blog_id"]) { + $this->ctrl->setParameter($this, "blog_id", $_REQUEST["blog_id"]); + $txt = $this->lng->txt("exc_direct_submit_blog"); + } else { + $this->ctrl->setParameter($this, "prtf_id", $_REQUEST["prtf_id"]); + $txt = $this->lng->txt("exc_direct_submit_portfolio"); + } + $conf->setFormAction($this->ctrl->getFormAction($this, "directSubmit")); + + $conf->setHeaderText($txt); + $conf->setConfirm($this->lng->txt("exc_direct_submit"), "directSubmit"); + $conf->setCancel($this->lng->txt("exc_direct_no_submit"), "returnToParent"); + + $tpl->setContent($conf->getHTML()); + } + + protected function directSubmitObject() + { + if (!$this->submission->canSubmit()) { + ilUtil::sendInfo($this->lng->txt("exercise_time_over"), true); + $this->returnToParentObject(); + } + + $success = false; + + // submit current version of blog + if ($_REQUEST["blog_id"]) { + $success = $this->submitBlog($_REQUEST["blog_id"]); + $this->ctrl->setParameter($this, "blog_id", ""); + } + // submit current version of portfolio + elseif ($_REQUEST["prtf_id"]) { + $success = $this->submitPortfolio($_REQUEST["prtf_id"]); + $this->ctrl->setParameter($this, "prtf_id", ""); + } + + if ($success) { + ilUtil::sendSuccess($this->lng->txt("settings_saved"), true); + } else { + ilUtil::sendFailure($this->lng->txt("msg_failed"), true); + } + $this->ctrl->redirect($this, "returnToParent"); + } + + /** + * Submit blog for assignment + * + * @param int $a_blog_id + * @return bool + */ + public function submitBlog($a_blog_id) + { + if (!$this->submission->canSubmit()) { + return; + } + + $blog_id = $a_blog_id; + + include_once "Modules/Blog/classes/class.ilObjBlogGUI.php"; + $blog_gui = new ilObjBlogGUI($blog_id, ilObjBlogGUI::WORKSPACE_NODE_ID); + if ($blog_gui->object) { + $file = $blog_gui->buildExportFile(); + $size = filesize($file); + if ($size) { + $this->submission->deleteAllFiles(); + + $meta = array( + "name" => $blog_id, + "tmp_name" => $file, + "size" => $size + ); + $this->submission->uploadFile($meta, true); + + $this->handleNewUpload(); + return true; + } + } + return false; + } + + /** + * Submit portfolio for assignment + * + * @param int $a_portfolio_id + * @return bool + */ + public function submitPortfolio($a_portfolio_id) + { + if (!$this->submission->canSubmit()) { + return; + } + + $prtf_id = $a_portfolio_id; + + include_once "Modules/Portfolio/classes/class.ilObjPortfolio.php"; + $prtf = new ilObjPortfolio($prtf_id, false); + if ($prtf->getTitle()) { + include_once "Modules/Portfolio/classes/class.ilPortfolioHTMLExport.php"; + $export = new ilPortfolioHTMLExport(null, $prtf); + $file = $export->buildExportFile(); + $size = filesize($file); + if ($size) { + $this->submission->deleteAllFiles(); + + $meta = array( + "name" => $prtf_id, + "tmp_name" => $file, + "size" => $size + ); + $this->submission->uploadFile($meta, true); + + $this->handleNewUpload(); + return true; + } + } + return false; + } + + public static function initGUIForSubmit($a_ass_id, $a_user_id = null) + { + global $DIC; + + $ilUser = $DIC->user(); + + if (!$a_user_id) { + $a_user_id = $ilUser->getId(); + } + + include_once "Modules/Exercise/classes/class.ilObjExercise.php"; + include_once "Modules/Exercise/classes/class.ilExAssignment.php"; + include_once "Modules/Exercise/classes/class.ilExSubmission.php"; + + $ass = new ilExAssignment($a_ass_id); + $sub = new ilExSubmission($ass, $a_user_id); + $exc_id = $ass->getExerciseId(); + + // #11173 - ref_id is needed for notifications + $exc_ref_id = array_shift(ilObject::_getAllReferences($exc_id)); + $exc = new ilObjExercise($exc_ref_id, true); + + return new self($exc, $sub); + } } diff --git a/Modules/Exercise/classes/class.ilExSubmissionTextGUI.php b/Modules/Exercise/classes/class.ilExSubmissionTextGUI.php index 824799757afb5aa15efbbae53d3f5955c84a8c43..63bcbe77af3142bb2c0a79745bad0ab64efcf158 100644 --- a/Modules/Exercise/classes/class.ilExSubmissionTextGUI.php +++ b/Modules/Exercise/classes/class.ilExSubmissionTextGUI.php @@ -5,314 +5,284 @@ * Object-based submissions (ends up as static file) * * @author Jörg Lützenkirchen" . $md . "
", $a_output); - } - } + $this->tpl = $DIC["tpl"]; + $tpl = $DIC["tpl"]; - return $a_output; - } + parent::__construct("gdf", $a_id, $a_old_nr); + } + + /** + * Set glossary + * + * @param ilObjGlossary $a_val glossary + */ + public function setGlossary($a_val) + { + $this->glossary = $a_val; + } + + /** + * Get glossary + * + * @return ilObjGlossary glossary + */ + public function getGlossary() + { + return $this->glossary; + } + /** + * Output metadata + */ + public function postOutputProcessing($a_output) + { + if ($this->getOutputMode() == "print" && $this->glossary instanceof ilObjGlossary) { + include_once("./Modules/Glossary/classes/class.ilGlossaryDefinition.php"); + $term_id = ilGlossaryDefinition::_lookupTermId($this->getId()); + include_once("./Services/Object/classes/class.ilObjectMetaDataGUI.php"); + $mdgui = new ilObjectMetaDataGUI($this->glossary, "term", $term_id); + $md = $mdgui->getKeyValueList(); + if ($md != "") { + $a_output = str_replace("", "" . $md . "
", $a_output); + } + } -} -?> + return $a_output; + } +} diff --git a/Modules/Glossary/classes/class.ilGlossaryDefinition.php b/Modules/Glossary/classes/class.ilGlossaryDefinition.php index b96bc6111ccd493ae05acfee0b54003ddb4fe238..08393398027cf7961419d660911840e7627d5849 100755 --- a/Modules/Glossary/classes/class.ilGlossaryDefinition.php +++ b/Modules/Glossary/classes/class.ilGlossaryDefinition.php @@ -13,674 +13,653 @@ require_once("./Modules/Glossary/classes/class.ilGlossaryDefPage.php"); */ class ilGlossaryDefinition { - /** - * @var ilDB - */ - protected $db; - - /** - * @var ilObjUser - */ - protected $user; - - var $lng; - var $tpl; - - var $id; - var $term_id; - var $glo_id; - var $page_object; - var $short_text; - var $nr; - var $short_text_dirty = false; - - /** - * Constructor - * @access public - */ - function __construct($a_id = 0) - { - global $DIC; - - $this->db = $DIC->database(); - $this->user = $DIC->user(); - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - - $this->lng = $lng; - $this->tpl = $tpl; - - $this->id = $a_id; - if ($a_id != 0) - { - $this->read(); - } - } - - /** - * read data of content object - */ - function read() - { - $ilDB = $this->db; - - $q = "SELECT * FROM glossary_definition WHERE id = ". - $ilDB->quote($this->id, "integer"); - $def_set = $ilDB->query($q); - $def_rec = $ilDB->fetchAssoc($def_set); - - $this->setTermId($def_rec["term_id"]); - $this->setShortText($def_rec["short_text"]); - $this->setNr($def_rec["nr"]); - $this->setShortTextDirty($def_rec["short_text_dirty"]); - - $this->page_object = new ilGlossaryDefPage($this->id); - } - - function setId($a_id) - { - $this->id = $a_id; - } - - function getId() - { - return $this->id; - } - - function getType() - { - return "gdf"; - } - - function setTermId($a_term_id) - { - $this->term_id = $a_term_id; - } - - function getTermId() - { - return $this->term_id; - } - - function setShortText($a_text) - { - $this->short_text = $this->shortenShortText($a_text); - } - - function getShortText() - { - return $this->short_text; - } - - function setNr($a_nr) - { - $this->nr = $a_nr; - } - - function getNr() - { - return $this->nr; - } - - function assignPageObject(&$a_page_object) - { - $this->page_object = $a_page_object; - } - - function &getPageObject() - { - return $this->page_object; - } - - /** - * get title of content object - * - * @return string title - */ - function getTitle() - { - return $this->title; - } - - /** - * set title of content object - */ - function setTitle($a_title) - { - $this->title = $a_title; - } - - /** - * Get description - * - * @return string description - */ - function getDescription() - { - return $this->description; - } - - /** - * Set description - * - * @param string description - */ - function setDescription($a_description) - { - $this->description = $a_description; - } - - /** - * Set short text dirty - * - * @param boolean short text dirty - */ - function setShortTextDirty($a_val) - { - $this->short_text_dirty = $a_val; - } - - /** - * Get short text dirty - * - * @return boolean short text dirty - */ - function getShortTextDirty() - { - return $this->short_text_dirty; - } - /** - * Create definition - * - * @param boolean upload true/false - */ - function create($a_upload = false, $a_omit_page_creation = false) - { - $ilDB = $this->db; - - $term = new ilGlossaryTerm($this->getTermId()); - - $this->setId($ilDB->nextId("glossary_definition")); - - $ilAtomQuery = $ilDB->buildAtomQuery(); - $ilAtomQuery->addTableLock('glossary_definition'); - - $ilAtomQuery->addQueryCallable(function (ilDBInterface $ilDB) { - - // get maximum definition number - $q = "SELECT max(nr) AS max_nr FROM glossary_definition WHERE term_id = " . - $ilDB->quote($this->getTermId(), "integer"); - $max_set = $ilDB->query($q); - $max_rec = $ilDB->fetchAssoc($max_set); - $max = (int)$max_rec["max_nr"]; - - // insert new definition record - $ilDB->manipulate("INSERT INTO glossary_definition (id, term_id, short_text, nr, short_text_dirty)" . - " VALUES (" . - $ilDB->quote($this->getId(), "integer") . "," . - $ilDB->quote($this->getTermId(), "integer") . "," . - $ilDB->quote($this->getShortText(), "text") . ", " . - $ilDB->quote(($max + 1), "integer") . ", " . - $ilDB->quote($this->getShortTextDirty(), "integer") . - ")"); - - }); - - $ilAtomQuery->run(); - - // get number - $q = "SELECT nr FROM glossary_definition WHERE id = ". - $ilDB->quote($this->id, "integer"); - $def_set = $ilDB->query($q); - $def_rec = $ilDB->fetchAssoc($def_set); - $this->setNr($def_rec["nr"]); - - // meta data will be created by - // import parser - if (!$a_upload) - { - $this->createMetaData(); - } - - if (!$a_omit_page_creation) - { - $this->page_object = new ilGlossaryDefPage(); - $this->page_object->setId($this->getId()); - $this->page_object->setParentId($term->getGlossaryId()); - $this->page_object->create(); - } - } - - function delete() - { - $ilDB = $this->db; - - $ilAtomQuery = $ilDB->buildAtomQuery(); - $ilAtomQuery->addTableLock("glossary_definition"); - - $ilAtomQuery->addQueryCallable(function (ilDBInterface $ilDB){ - - // be sure to get the right number - $q = "SELECT * FROM glossary_definition WHERE id = ". - $ilDB->quote($this->id, "integer"); - $def_set = $ilDB->query($q); - $def_rec = $ilDB->fetchAssoc($def_set); - $this->setNr($def_rec["nr"]); - - // update numbers of other definitions - $ilDB->manipulate("UPDATE glossary_definition SET ". - " nr = nr - 1 ". - " WHERE term_id = ".$ilDB->quote($this->getTermId(), "integer")." ". - " AND nr > ".$ilDB->quote($this->getNr(), "integer")); - - // delete current definition - $ilDB->manipulate("DELETE FROM glossary_definition ". - " WHERE id = ".$ilDB->quote($this->getId(), "integer")); - - }); - $ilAtomQuery->run(); - - // delete page and meta data - $this->page_object->delete(); - - // delete meta data - $this->deleteMetaData(); - } - - - function moveUp() - { - $ilDB = $this->db; - - $ilAtomQuery = $ilDB->buildAtomQuery(); - $ilAtomQuery->addTableLock('glossary_definition'); - - $ilAtomQuery->addQueryCallable(function (ilDBInterface $ilDB) { - - // be sure to get the right number - $q = "SELECT * FROM glossary_definition WHERE id = " . - $ilDB->quote($this->id, "integer"); - $def_set = $ilDB->query($q); - $def_rec = $ilDB->fetchAssoc($def_set); - $this->setNr($def_rec["nr"]); - - if ($this->getNr() < 2) { - return; - } - - // update numbers of other definitions - $ilDB->manipulate("UPDATE glossary_definition SET " . - " nr = nr + 1 " . - " WHERE term_id = " . $ilDB->quote($this->getTermId(), "integer") . " " . - " AND nr = " . $ilDB->quote(($this->getNr() - 1), "integer")); - - // delete current definition - $ilDB->manipulate("UPDATE glossary_definition SET " . - " nr = nr - 1 " . - " WHERE term_id = " . $ilDB->quote($this->getTermId(), "integer") . " " . - " AND id = " . $ilDB->quote($this->getId(), "integer")); - - }); - $ilAtomQuery->run(); - } - - function moveDown() - { - $ilDB = $this->db; - - $ilAtomQuery = $ilDB->buildAtomQuery(); - $ilAtomQuery->addTableLock('glossary_definition'); - - $ilAtomQuery->addQueryCallable(function(ilDBInterface $ilDB){ - - // be sure to get the right number - $q = "SELECT * FROM glossary_definition WHERE id = ". - $ilDB->quote($this->id, "integer"); - $def_set = $ilDB->query($q); - $def_rec = $ilDB->fetchAssoc($def_set); - $this->setNr($def_rec["nr"]); - - // get max number - $q = "SELECT max(nr) as max_nr FROM glossary_definition WHERE term_id = ". - $ilDB->quote($this->getTermId(), "integer"); - $max_set = $ilDB->query($q); - $max_rec = $ilDB->fetchAssoc($max_set); - - if ($this->getNr() >= $max_rec["max_nr"]) - { - return; - } - - // update numbers of other definitions - $ilDB->manipulate("UPDATE glossary_definition SET ". - " nr = nr - 1 ". - " WHERE term_id = ".$ilDB->quote($this->getTermId(), "integer")." ". - " AND nr = ".$ilDB->quote(($this->getNr() + 1), "integer")); - - // delete current definition - $ilDB->manipulate("UPDATE glossary_definition SET ". - " nr = nr + 1 ". - " WHERE term_id = ".$ilDB->quote($this->getTermId(), "integer")." ". - " AND id = ".$ilDB->quote($this->getId(), "integer")); - - }); - - $ilAtomQuery->run(); - } - - - function update() - { - $ilDB = $this->db; - - $this->updateMetaData(); - - $ilDB->manipulate("UPDATE glossary_definition SET ". - " term_id = ".$ilDB->quote($this->getTermId(), "integer").", ". - " nr = ".$ilDB->quote($this->getNr(), "integer").", ". - " short_text = ".$ilDB->quote($this->getShortText(), "text").", ". - " short_text_dirty = ".$ilDB->quote($this->getShortTextDirty(), "integer")." ". - " WHERE id = ".$ilDB->quote($this->getId(), "integer")); - } - - /** - * Shorten short text - * - * @param - * @return - */ - function shortenShortText($text) - { - $a_length = 196; - - if ($this->getTermId() > 0) - { - include_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); - include_once("./Modules/Glossary/classes/class.ilGlossaryTerm.php"); - $glo_id = ilGlossaryTerm::_lookGlossaryId($this->getTermId()); - $snippet_length = ilObjGlossary::lookupSnippetLength($glo_id); - if ($snippet_length > 0) - { - $a_length = $snippet_length; - } - } - - $text = str_replace("".print_r($a_mapping, true).""; exit; - // get all glossaries of the import - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); - $maps = $a_mapping->getMappingsOfEntity("Modules/Glossary", "glo"); - foreach ($maps as $old => $new) - { - if ($old != "new_id" && (int) $old > 0) - { - // get all new taxonomys of this object - $new_tax_ids = $a_mapping->getMapping("Services/Taxonomy", "tax_usage_of_obj", $old); - if($new_tax_ids !== false) - { - $tax_ids = explode(":", $new_tax_ids); - foreach ($tax_ids as $tid) - { - ilObjTaxonomy::saveUsage($tid, $new); - } - } - - // advmd column order - if ($this->exportedFromSameInstallation()) - { - include_once("./Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php"); - $advmdco = $a_mapping->getMappingsOfEntity("Modules/Glossary", "advmd_col_order"); - foreach ($advmdco as $id => $order) - { - $id = explode(":", $id); - $field_glo_id = $id[0]; - $field_id = $id[1]; - if ($field_glo_id == $old) - { - // #17454 - $new_local_id = $a_mapping->getMapping("Services/AdvancedMetaData", "lfld", $field_id); - if($new_local_id) - { - $field_id = $new_local_id; - } - ilGlossaryAdvMetaDataAdapter::writeColumnOrder($new, $field_id, $order); - } - } - } - } - } - } - + /** + * Initialisation + */ + public function init() + { + include_once("./Modules/Glossary/classes/class.ilGlossaryDataSet.php"); + $this->ds = new ilGlossaryDataSet(); + $this->ds->setDSPrefix("ds"); + $this->config = $this->getImport()->getConfig("Modules/Glossary"); + } + + /** + * Import XML + * + * @param + * @return + */ + public function importXmlRepresentation($a_entity, $a_id, $a_xml, $a_mapping) + { + if ($a_entity == "glo") { + // case i container + if ($new_id = $a_mapping->getMapping('Services/Container', 'objs', $a_id)) { + $newObj = ilObjectFactory::getInstanceByObjId($new_id, false); + } + + // in the new version (5.1) we are also here, but the following file should not exist + // if being exported with 5.1 or higher + $xml_file = $this->getImportDirectory() . '/' . basename($this->getImportDirectory()) . '.xml'; + $GLOBALS['ilLog']->write(__METHOD__ . ': Using XML file ' . $xml_file); + + // old school import + if (file_exists($xml_file)) { + if (!is_object($newObj)) { + // create and insert object in objecttree + include_once("./Modules/Glossary/classes/class.ilObjGlossary.php"); + $newObj = new ilObjGlossary(); + $newObj->setType("glo"); + $newObj->setTitle(basename($this->getImportDirectory())); + $newObj->create(true); + } + + include_once './Modules/LearningModule/classes/class.ilContObjParser.php'; + $contParser = new ilContObjParser( + $newObj, + $xml_file, + basename($this->getImportDirectory()) + ); + + $contParser->startParsing(); + + ilObject::_writeImportId($newObj->getId(), $newObj->getImportId()); + + // write term map for taxonomies to mapping object + $term_map = $contParser->getGlossaryTermMap(); + foreach ($term_map as $k => $v) { + $a_mapping->addMapping( + "Services/Taxonomy", + "tax_item", + "glo:term:" . $k, + $v + ); + + // this is since 4.3 does not export these ids but 4.4 tax node assignment needs it + $a_mapping->addMapping( + "Services/Taxonomy", + "tax_item_obj_id", + "glo:term:" . $k, + $newObj->getId() + ); + + $a_mapping->addMapping( + "Services/AdvancedMetaData", + "advmd_sub_item", + "advmd:term:" . $k, + $v + ); + } + + $a_mapping->addMapping("Modules/Glossary", "glo", $a_id, $newObj->getId()); + $a_mapping->addMapping("Services/AdvancedMetaData", "parent", $a_id, $newObj->getId()); + + $this->current_glo = $newObj; + } else { + // necessary? + // ilObject::_writeImportId($newObj->getId(), $newObj->getImportId()); + include_once("./Services/DataSet/classes/class.ilDataSetImportParser.php"); + $parser = new ilDataSetImportParser( + $a_entity, + $this->getSchemaVersion(), + $a_xml, + $this->ds, + $a_mapping + ); + + // in the new version the mapping above is done in the dataset + } + } + } + + /** + * Final processing + * + * @param + * @return + */ + public function finalProcessing($a_mapping) + { + //echo "
".print_r($a_mapping, true).""; exit; + // get all glossaries of the import + include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); + $maps = $a_mapping->getMappingsOfEntity("Modules/Glossary", "glo"); + foreach ($maps as $old => $new) { + if ($old != "new_id" && (int) $old > 0) { + // get all new taxonomys of this object + $new_tax_ids = $a_mapping->getMapping("Services/Taxonomy", "tax_usage_of_obj", $old); + if ($new_tax_ids !== false) { + $tax_ids = explode(":", $new_tax_ids); + foreach ($tax_ids as $tid) { + ilObjTaxonomy::saveUsage($tid, $new); + } + } + + // advmd column order + if ($this->exportedFromSameInstallation()) { + include_once("./Modules/Glossary/classes/class.ilGlossaryAdvMetaDataAdapter.php"); + $advmdco = $a_mapping->getMappingsOfEntity("Modules/Glossary", "advmd_col_order"); + foreach ($advmdco as $id => $order) { + $id = explode(":", $id); + $field_glo_id = $id[0]; + $field_id = $id[1]; + if ($field_glo_id == $old) { + // #17454 + $new_local_id = $a_mapping->getMapping("Services/AdvancedMetaData", "lfld", $field_id); + if ($new_local_id) { + $field_id = $new_local_id; + } + ilGlossaryAdvMetaDataAdapter::writeColumnOrder($new, $field_id, $order); + } + } + } + } + } + } } -?> \ No newline at end of file diff --git a/Modules/Glossary/classes/class.ilGlossaryLocatorGUI.php b/Modules/Glossary/classes/class.ilGlossaryLocatorGUI.php index 7aa3ac870bfe8d888fdff34ddb51781ba965ab81..95ee48c466842018b7bb6dfde03bfc0fcdba4cd9 100755 --- a/Modules/Glossary/classes/class.ilGlossaryLocatorGUI.php +++ b/Modules/Glossary/classes/class.ilGlossaryLocatorGUI.php @@ -12,121 +12,112 @@ */ class ilGlossaryLocatorGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilLocatorGUI - */ - protected $locator; - - var $mode; - var $temp_var; - var $tree; - var $obj; - var $lng; - var $tpl; - - - function __construct() - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->locator = $DIC["ilLocator"]; - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - $tree = $DIC->repositoryTree(); - - $this->mode = "edit"; - $this->temp_var = "LOCATOR"; - $this->lng = $lng; - $this->tpl = $tpl; - $this->tree = $tree; - } - - function setTemplateVariable($a_temp_var) - { - $this->temp_var = $a_temp_var; - } - - function setTerm(&$a_term) - { - $this->term = $a_term; - } - - function setGlossary(&$a_glossary) - { - $this->glossary = $a_glossary; - } - - function setDefinition(&$a_def) - { - $this->definition = $a_def; - } - - function setMode($a_mode) - { - $this->mode = $a_mode; - } - - /** - * display locator - */ - function display() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilLocator = $this->locator; - $tpl = $this->tpl; - - // repository links - $ilLocator->addRepositoryItems(); - - // glossary link - $title = $this->glossary->getTitle(); - if ($this->mode == "edit") - { - $link = $ilCtrl->getLinkTargetByClass("ilobjglossarygui", "listTerms"); - } - else - { - $ilCtrl->setParameterByClass("ilglossarypresentationgui", "term_id", ""); - $link = $ilCtrl->getLinkTargetByClass("ilglossarypresentationgui"); - if (is_object($this->term)) - { - $ilCtrl->setParameterByClass("ilglossarypresentationgui", "term_id", $this->term->getId()); - } - } - $ilLocator->addItem($title, $link, ""); - - if (is_object($this->term) && $this->mode != "edit") - { - $ilCtrl->setParameterByClass("ilglossarypresentationgui", "term_id", $this->term->getId()); - $ilLocator->addItem($this->term->getTerm(), - $ilCtrl->getLinkTargetByClass("ilglossarypresentationgui", "listDefinitions")); - $ilCtrl->setParameterByClass("ilglossarypresentationgui", "term_id", $_GET["term_id"]); - } - - if (is_object($this->definition)) - { - $title = $this->term->getTerm()." (".$this->lng->txt("cont_definition")." ".$this->definition->getNr().")"; - if ($this->mode == "edit") - { - $link = $ilCtrl->getLinkTargetByClass("ilglossarydefpagegui", "edit"); - } - else - { - $ilCtrl->setParameterByClass("ilglossarypresentationgui", "def", $_GET["def"]); - $link = $ilCtrl->getLinkTargetByClass("ilglossarypresentationgui", "view"); - } - $ilLocator->addItem($title, $link); - } - - $tpl->setLocator(); - } - + /** + * @var ilCtrl + */ + protected $ctrl; + + /** + * @var ilLocatorGUI + */ + protected $locator; + + public $mode; + public $temp_var; + public $tree; + public $obj; + public $lng; + public $tpl; + + + public function __construct() + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->locator = $DIC["ilLocator"]; + $lng = $DIC->language(); + $tpl = $DIC["tpl"]; + $tree = $DIC->repositoryTree(); + + $this->mode = "edit"; + $this->temp_var = "LOCATOR"; + $this->lng = $lng; + $this->tpl = $tpl; + $this->tree = $tree; + } + + public function setTemplateVariable($a_temp_var) + { + $this->temp_var = $a_temp_var; + } + + public function setTerm(&$a_term) + { + $this->term = $a_term; + } + + public function setGlossary(&$a_glossary) + { + $this->glossary = $a_glossary; + } + + public function setDefinition(&$a_def) + { + $this->definition = $a_def; + } + + public function setMode($a_mode) + { + $this->mode = $a_mode; + } + + /** + * display locator + */ + public function display() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilLocator = $this->locator; + $tpl = $this->tpl; + + // repository links + $ilLocator->addRepositoryItems(); + + // glossary link + $title = $this->glossary->getTitle(); + if ($this->mode == "edit") { + $link = $ilCtrl->getLinkTargetByClass("ilobjglossarygui", "listTerms"); + } else { + $ilCtrl->setParameterByClass("ilglossarypresentationgui", "term_id", ""); + $link = $ilCtrl->getLinkTargetByClass("ilglossarypresentationgui"); + if (is_object($this->term)) { + $ilCtrl->setParameterByClass("ilglossarypresentationgui", "term_id", $this->term->getId()); + } + } + $ilLocator->addItem($title, $link, ""); + + if (is_object($this->term) && $this->mode != "edit") { + $ilCtrl->setParameterByClass("ilglossarypresentationgui", "term_id", $this->term->getId()); + $ilLocator->addItem( + $this->term->getTerm(), + $ilCtrl->getLinkTargetByClass("ilglossarypresentationgui", "listDefinitions") + ); + $ilCtrl->setParameterByClass("ilglossarypresentationgui", "term_id", $_GET["term_id"]); + } + + if (is_object($this->definition)) { + $title = $this->term->getTerm() . " (" . $this->lng->txt("cont_definition") . " " . $this->definition->getNr() . ")"; + if ($this->mode == "edit") { + $link = $ilCtrl->getLinkTargetByClass("ilglossarydefpagegui", "edit"); + } else { + $ilCtrl->setParameterByClass("ilglossarypresentationgui", "def", $_GET["def"]); + $link = $ilCtrl->getLinkTargetByClass("ilglossarypresentationgui", "view"); + } + $ilLocator->addItem($title, $link); + } + + $tpl->setLocator(); + } } -?> diff --git a/Modules/Glossary/classes/class.ilGlossaryPresentationGUI.php b/Modules/Glossary/classes/class.ilGlossaryPresentationGUI.php index 4f54bdd9bbe8809c761bf096a52a63942c6b1027..1935ed16336ca2126a7afd7bb370caa31a0a295c 100755 --- a/Modules/Glossary/classes/class.ilGlossaryPresentationGUI.php +++ b/Modules/Glossary/classes/class.ilGlossaryPresentationGUI.php @@ -23,1612 +23,1520 @@ require_once("./Services/COPage/classes/class.ilPCParagraph.php"); */ class ilGlossaryPresentationGUI { - /** - * @var ilCtrl - */ - protected $ctrl; - - /** - * @var ilTabsGUI - */ - protected $tabs_gui; - - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilErrorHandling - */ - protected $error; - - /** - * @var ilNavigationHistory - */ - protected $nav_history; - - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilHelpGUI - */ - protected $help; - - var $admin_tabs; - var $glossary; - var $tpl; - var $lng; - - /** - * Constructor - * @access public - */ - function __construct() - { - global $DIC; - - $this->access = $DIC->access(); - $this->error = $DIC["ilErr"]; - $this->nav_history = $DIC["ilNavigationHistory"]; - $this->toolbar = $DIC->toolbar(); - $this->user = $DIC->user(); - $this->help = $DIC["ilHelp"]; - $lng = $DIC->language(); - $tpl = $DIC["tpl"]; - $ilCtrl = $DIC->ctrl(); - $ilTabs = $DIC->tabs(); - - $this->tabs_gui = $ilTabs; - $this->tpl = $tpl; - $this->lng = $lng; - $this->ctrl = $ilCtrl; - $this->offline = false; - $this->ctrl->saveParameter($this, array("ref_id", "letter", "tax_node")); - - // Todo: check lm id - include_once("./Modules/Glossary/classes/class.ilObjGlossaryGUI.php"); - $this->glossary_gui = new ilObjGlossaryGUI("", $_GET["ref_id"], true, ""); - $this->glossary = $this->glossary_gui->object; - - // determine term id and check whether it is valid (belongs to - // current glossary or a virtual (online) sub-glossary) - $this->term_id = (int) $_GET["term_id"]; - $glo_ids = $this->glossary->getAllGlossaryIds(); - if (!is_array($glo_ids)) - { - $glo_ids = array($glo_ids); - } - $term_glo_id = ilGlossaryTerm::_lookGlossaryID($this->term_id); - include_once("./Modules/Glossary/classes/class.ilGlossaryTermReferences.php"); - if (!in_array($term_glo_id, $glo_ids) && !ilGlossaryTermReferences::isReferenced($glo_ids, $this->term_id)) - { - if ((int) $this->term_id > 0) - { - include_once("./Modules/Glossary/exceptions/class.ilGlossaryException.php"); - throw new ilGlossaryException("Term ID does not match the glossary."); - } - $this->term_id = ""; - } - - $this->tax_node = 0; - $this->tax_id = $this->glossary->getTaxonomyId(); - if ($this->tax_id > 0 && $this->glossary->getShowTaxonomy()) - { - include_once("./Services/Taxonomy/classes/class.ilObjTaxonomy.php"); - $this->tax = new ilObjTaxonomy($this->tax_id); - } - if ((int) $_GET["tax_node"] > 1 && $this->tax->getTree()->readRootId() != $_GET["tax_node"]) - { - $this->tax_node = (int) $_GET["tax_node"]; - } - } - - - /** - * set offline mode (content is generated for offline package) - */ - function setOfflineMode($a_offline = true) - { - $this->offline = $a_offline; - } - - /** - * checks wether offline content generation is activated - */ - function offlineMode() - { - return $this->offline; - } - - /** - * Set offline directory. - */ - function setOfflineDirectory($a_dir) - { - $this->offline_dir = $a_dir; - } - - - /** - * Get offline directory. - */ - function getOfflineDirectory() - { - return $this->offline_dir; - } - - - /** - * execute command - */ - function executeCommand() - { - $lng = $this->lng; - $ilAccess = $this->access; - $ilErr = $this->error; - - $lng->loadLanguageModule("content"); - - $next_class = $this->ctrl->getNextClass($this); - $cmd = $this->ctrl->getCmd("listTerms"); - - // check write permission - if (!$ilAccess->checkAccess("read", "", $_GET["ref_id"]) && - !($ilAccess->checkAccess("visible", "", $_GET["ref_id"]) && - ($cmd == "infoScreen" || strtolower($next_class) == "ilinfoscreengui"))) - { - $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); - } - - if ($cmd != "listDefinitions") - { - $this->prepareOutput(); - } - - switch($next_class) - { - case "ilnotegui": - $this->setTabs(); - $ret = $this->listDefinitions(); - break; - - case "ilinfoscreengui": - $ret = $this->outputInfoScreen(); - break; - - case "ilpresentationlisttablegui": - $prtab = $this->getPresentationTable(); - $this->ctrl->forwardCommand($prtab); - return; - break; - - default: - $ret = $this->$cmd(); - break; - } - $this->tpl->show(); - } - - function prepareOutput() - { - $this->tpl->getStandardTemplate(); - $title = $this->glossary->getTitle(); - - $this->tpl->setTitle($title); - $this->tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); - - $this->setLocator(); - } - - - /** - * List all terms - */ - function listTerms() - { - $ilNavigationHistory = $this->nav_history; - $ilAccess = $this->access; - $lng = $this->lng; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $ilTabs = $this->tabs_gui; - $ilErr = $this->error; - - - if (!$ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); - } - - if (!$this->offlineMode()) - { - $ilNavigationHistory->addItem($_GET["ref_id"], - $this->ctrl->getLinkTarget($this, "listTerms"), "glo"); - - // alphabetical navigation - include_once("./Services/Form/classes/class.ilAlphabetInputGUI.php"); - $ai = new ilAlphabetInputGUI($lng->txt("glo_quick_navigation"), "first"); - - $ai->setFixDBUmlauts(true); - - $first_letters = $this->glossary->getFirstLetters($this->tax_node); - if (!is_array($first_letters)) - { - $first_letters = []; - } - if (!in_array($_GET["letter"], $first_letters)) - { - $first_letters[] = ilUtil::stripSlashes($_GET["letter"]); - } - $ai->setLetters($first_letters); - - $ai->setParentCommand($this, "chooseLetter"); - $ai->setHighlighted($_GET["letter"]); - $ilToolbar->addInputItem($ai, true); - - } - - $ret = $this->listTermByGiven(); - $ilCtrl->setParameter($this, "term_id", ""); - - $ilTabs->activateTab("terms"); - - // show taxonomy - $this->showTaxonomy(); - - return $ret; - } - - /** - * list glossary terms - */ - function listTermByGiven() - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $lng = $this->lng; - $tpl = $this->tpl; - - if (!$ilAccess->checkAccess("read", "", $_GET["ref_id"])) - { - $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); - } - - $this->lng->loadLanguageModule("meta"); - - $this->setTabs(); - - // load template for table -// $this->tpl->addBlockfile("ADM_CONTENT", "adm_content", "tpl.table.html"); - - $oldoffset = (is_numeric ($_GET["oldoffset"]))?$_GET["oldoffset"]:$_GET["offset"]; - - if ($this->glossary->getPresentationMode() == "full_def") - { - // content style - $this->tpl->setCurrentBlock("ContentStyle"); - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->glossary->getStyleSheetId())); - } - else - { - $this->tpl->setVariable("LOCATION_CONTENT_STYLESHEET","content.css"); - } - $this->tpl->parseCurrentBlock(); - - // syntax style - $this->tpl->setCurrentBlock("SyntaxStyle"); - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - } - else - { - $this->tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - "syntaxhighlight.css"); - } - $this->tpl->parseCurrentBlock(); - } - - $table = $this->getPresentationTable(); - - if (!$this->offlineMode()) - { -// $tpl->setContent($table->getHTML()); - $tpl->setContent($ilCtrl->getHTML($table)); - } - else - { - $this->tpl->setVariable("ADM_CONTENT", $table->getHTML()); - return $this->tpl->get(); - } - } - - /** - * Get presentation table - * - * @param - * @return - */ - function getPresentationTable() - { - include_once("./Modules/Glossary/classes/class.ilPresentationListTableGUI.php"); - $table = new ilPresentationListTableGUI($this, "listTerms", $this->glossary, - $this->offlineMode(), $this->tax_node, $this->glossary->getTaxonomyId()); - return $table; - } - - /** - * Apply filter - */ - function applyFilter() - { - $ilTabs = $this->tabs_gui; - - $prtab = $this->getPresentationTable(); - $prtab->resetOffset(); - $prtab->writeFilterToSession(); - $this->listTerms(); - - } - - /** - * Reset filter - * (note: this function existed before data table filter has been introduced - */ - function resetFilter() - { - $prtab = $this->getPresentationTable(); - $prtab->resetOffset(); - $prtab->resetFilter(); - $this->listTerms(); - } - - /** - * list definitions of a term - */ - function listDefinitions($a_ref_id = 0, $a_term_id = 0, $a_get_html = false, $a_page_mode = IL_PAGE_PRESENTATION) - { - $ilUser = $this->user; - $ilAccess = $this->access; - $lng = $this->lng; - $ilErr = $this->error; - - if ($a_ref_id == 0) - { - $ref_id = (int) $_GET["ref_id"]; - } - else - { - $ref_id = $a_ref_id; - } - if ($a_term_id == 0) - { - $term_id = $this->term_id; - } - else - { - $term_id = $a_term_id; - } - - if (!$ilAccess->checkAccess("read", "", $ref_id)) - { - $ilErr->raiseError($lng->txt("permission_denied"), $ilErr->MESSAGE); - } - - // tabs - if ($this->glossary->getPresentationMode() != "full_def") - { - $this->showDefinitionTabs("term_content"); - } - - $term = new ilGlossaryTerm($term_id); - - if (!$a_get_html) - { - $tpl = $this->tpl; - - require_once("./Modules/Glossary/classes/class.ilGlossaryDefPageGUI.php"); - $tpl->getStandardTemplate(); -// $this->setTabs(); - - if ($this->offlineMode()) - { - $style_name = $ilUser->prefs["style"].".css";; - $tpl->setVariable("LOCATION_STYLESHEET","./".$style_name); - } - else - { - $this->setLocator(); - } - - // content style - $tpl->setCurrentBlock("ContentStyle"); - if (!$this->offlineMode()) - { - $tpl->setVariable("LOCATION_CONTENT_STYLESHEET", - ilObjStyleSheet::getContentStylePath($this->glossary->getStyleSheetId())); - } - else - { - $tpl->setVariable("LOCATION_CONTENT_STYLESHEET","content.css"); - } - $tpl->parseCurrentBlock(); - - // syntax style - $tpl->setCurrentBlock("SyntaxStyle"); - if (!$this->offlineMode()) - { - $tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - } - else - { - $tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - "syntaxhighlight.css"); - } - $tpl->parseCurrentBlock(); - - $tpl->setTitleIcon(ilUtil::getImagePath("icon_glo.svg")); - $tpl->setTitle($this->lng->txt("cont_term").": ".$term->getTerm()); - - // advmd block - $cmd = null; - if($ilAccess->checkAccess("write", "", $_GET["ref_id"])) - { - $cmd = array("edit" => $this->ctrl->getLinkTargetByClass(array("ilglossaryeditorgui", "ilobjglossarygui", "ilglossarytermgui", "ilobjectmetadatagui"), "")); - } - include_once "Services/Object/classes/class.ilObjectMetaDataGUI.php"; - $mdgui = new ilObjectMetaDataGUI($this->glossary, "term", $term->getId()); - $tpl->setRightContent($mdgui->getBlockHTML($cmd)); - - // load template for table - $tpl->addBlockfile("ADM_CONTENT", "def_list", "tpl.glossary_definition_list.html", "Modules/Glossary"); - } - else - { - $tpl = new ilTemplate("tpl.glossary_definition_list.html", true, true, "Modules/Glossary"); - } - - $defs = ilGlossaryDefinition::getDefinitionList($term_id); - $tpl->setVariable("TXT_TERM", $term->getTerm()); - $this->mobs = array(); - - // toc - if (count($defs) > 1 && $a_page_mode == IL_PAGE_PRESENTATION) - { - $tpl->setCurrentBlock("toc"); - for($j=1; $j<=count($defs); $j++) - { - $tpl->setCurrentBlock("toc_item"); - $tpl->setVariable("TOC_DEF_NR", $j); - $tpl->setVariable("TOC_DEF", $lng->txt("cont_definition")); - $tpl->parseCurrentBlock(); - } - $tpl->setCurrentBlock("toc"); - $tpl->parseCurrentBlock(); - } - - for($j=0; $j
"; - echo htmlentities($this->xml->xmlDumpMem($format)); - echo ""; - */ - - // dump xml document to file - $this->xml->xmlDumpFile($this->export_dir."/".$this->subdir."/".$this->filename - , false); - - // help export (workaround to use ref id here) - if (ilObjContentObject::isOnlineHelpModule((int) $_GET["ref_id"])) - { - include_once("./Services/Export/classes/class.ilExport.php"); - $exp = new ilExport(); - $exp->exportEntity("help", $this->cont_obj->getId(), "4.3.0", "Services/Help", - "OnlineHelp", $this->export_dir."/".$this->subdir); - } - - // zip the file - ilUtil::zip($this->export_dir."/".$this->subdir, - $this->export_dir."/".$this->subdir.".zip"); - - // destroy writer object - $this->xml->_XmlWriter; - - $expLog->write(date("[y-m-d H:i:s] ")."Finished Export"); - - return $this->export_dir."/".$this->subdir.".zip"; - } - - /** - * build pdf offline file - */ - function buildExportFilePDF() - { - die("deprecated."); - } - - /** - * build html package - */ - function buildExportFileHTML() - { - // create directories - if ($this->lang == "") - { - $this->cont_obj->createExportDirectory("html"); - } - else - { - $this->cont_obj->createExportDirectory("html_".$this->lang); - } - - - // get html content - $this->cont_obj->exportHTML($this->export_dir."/".$this->subdir, $expLog, true, "html", $this->lang); - } - - /** - * build scorm package - */ - function buildExportFileSCORM() - { - // create directories - $this->cont_obj->createExportDirectory("scorm"); - - // get html content - $this->cont_obj->exportSCORM($this->export_dir."/".$this->subdir, $expLog); - } - + public $err; // error object + public $db; // database object + public $cont_obj; // content object (learning module | digilib book) + public $inst_id; // installation id + public $mode; + + /** + * Constructor + * @access public + */ + public function __construct(&$a_cont_obj, $a_mode = "xml", $a_lang = "") + { + global $DIC; + + $ilErr = $DIC["ilErr"]; + $ilDB = $DIC->database(); + + $this->cont_obj = $a_cont_obj; + + $this->err = $ilErr; + $this->db = $ilDB; + $this->mode = $a_mode; + $this->lang = $a_lang; + + $this->inst_id = IL_INST_ID; + + $date = time(); + switch ($this->mode) { + case "html": + if ($this->lang == "") { + $this->export_dir = $this->cont_obj->getExportDirectory("html"); + } else { + $this->export_dir = $this->cont_obj->getExportDirectory("html_" . $this->lang); + } + $this->subdir = $this->cont_obj->getType() . "_" . $this->cont_obj->getId(); + $this->filename = $this->subdir . ".zip"; + break; + + case "scorm": + $this->export_dir = $this->cont_obj->getExportDirectory("scorm"); + $this->subdir = $this->cont_obj->getType() . "_" . $this->cont_obj->getId(); + $this->filename = $this->subdir . ".zip"; + break; + + case "pdf": + $this->export_dir = $this->cont_obj->getOfflineDirectory(); + $this->subdir = $date . "__" . $this->inst_id . "__" . + $this->cont_obj->getType() . "_" . $this->cont_obj->getId(); + $this->filename = $this->subdir . ".fo"; + break; + + default: + $this->export_dir = $this->cont_obj->getExportDirectory(); + $this->subdir = $date . "__" . $this->inst_id . "__" . + $this->cont_obj->getType() . "_" . $this->cont_obj->getId(); + $this->filename = $this->subdir . ".xml"; + break; + } + } + + public function getInstId() + { + return $this->inst_id; + } + + /** + * build export file (complete zip file) + * + * @access public + * @return + */ + public function buildExportFile($a_mode = "") + { + switch ($this->mode) { + case "html": + $this->buildExportFileHTML(); + break; + + case "scorm": + $this->buildExportFileSCORM(); + break; + + case "pdf": + $this->buildExportFilePDF(); + break; + + default: + return $this->buildExportFileXML($a_mode); + break; + } + } + + /** + * build xml export file + */ + public function buildExportFileXML($a_mode = "") + { + if (in_array($a_mode, array("master", "masternomedia"))) { + include_once("./Services/Export/classes/class.ilExport.php"); + $exp = new ilExport(); + $conf = $exp->getConfig("Modules/LearningModule"); + $conf->setMasterLanguageOnly(true, ($a_mode == "master")); + $exp->exportObject($this->cont_obj->getType(), $this->cont_obj->getId(), "5.1.0"); + return; + } + + require_once("./Services/Xml/classes/class.ilXmlWriter.php"); + + $this->xml = new ilXmlWriter; + + // set dtd definition + $this->xml->xmlSetDtdDef(""); + + // set generated comment + $this->xml->xmlSetGenCmt("Export of ILIAS Content Module " . + $this->cont_obj->getId() . " of installation " . $this->inst . "."); + + // set xml header + $this->xml->xmlHeader(); + + // create directories + $this->cont_obj->createExportDirectory(); + ilUtil::makeDir($this->export_dir . "/" . $this->subdir); + ilUtil::makeDir($this->export_dir . "/" . $this->subdir . "/objects"); + + // get Log File + $expDir = $this->cont_obj->getExportDirectory(); + include_once './Services/Logging/classes/class.ilLog.php'; + $expLog = new ilLog($expDir, "export.log"); + $expLog->delete(); + $expLog->setLogFormat(""); + $expLog->write(date("[y-m-d H:i:s] ") . "Start Export"); + + // get xml content + $this->cont_obj->exportXML( + $this->xml, + $this->inst_id, + $this->export_dir . "/" . $this->subdir, + $expLog + ); + + // export style + if ($this->cont_obj->getStyleSheetId() > 0) { + include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); + $style_obj = new ilObjStyleSheet($this->cont_obj->getStyleSheetId(), false); + //$style_obj->exportXML($this->export_dir."/".$this->subdir); + $style_obj->setExportSubDir("style"); + $style_file = $style_obj->export(); + if (is_file($style_file)) { + copy($style_file, $this->export_dir . "/" . $this->subdir . "/style.zip"); + } + } + + // dump xml document to screen (only for debugging reasons) + /* + echo "
"; + echo htmlentities($this->xml->xmlDumpMem($format)); + echo ""; + */ + + // dump xml document to file + $this->xml->xmlDumpFile($this->export_dir . "/" . $this->subdir . "/" . $this->filename, false); + + // help export (workaround to use ref id here) + if (ilObjContentObject::isOnlineHelpModule((int) $_GET["ref_id"])) { + include_once("./Services/Export/classes/class.ilExport.php"); + $exp = new ilExport(); + $exp->exportEntity( + "help", + $this->cont_obj->getId(), + "4.3.0", + "Services/Help", + "OnlineHelp", + $this->export_dir . "/" . $this->subdir + ); + } + + // zip the file + ilUtil::zip( + $this->export_dir . "/" . $this->subdir, + $this->export_dir . "/" . $this->subdir . ".zip" + ); + + // destroy writer object + $this->xml->_XmlWriter; + + $expLog->write(date("[y-m-d H:i:s] ") . "Finished Export"); + + return $this->export_dir . "/" . $this->subdir . ".zip"; + } + + /** + * build pdf offline file + */ + public function buildExportFilePDF() + { + die("deprecated."); + } + + /** + * build html package + */ + public function buildExportFileHTML() + { + // create directories + if ($this->lang == "") { + $this->cont_obj->createExportDirectory("html"); + } else { + $this->cont_obj->createExportDirectory("html_" . $this->lang); + } + + + // get html content + $this->cont_obj->exportHTML($this->export_dir . "/" . $this->subdir, $expLog, true, "html", $this->lang); + } + + /** + * build scorm package + */ + public function buildExportFileSCORM() + { + // create directories + $this->cont_obj->createExportDirectory("scorm"); + + // get html content + $this->cont_obj->exportSCORM($this->export_dir . "/" . $this->subdir, $expLog); + } } - -?> diff --git a/Modules/LearningModule/classes/class.ilECSLearningModuleSettings.php b/Modules/LearningModule/classes/class.ilECSLearningModuleSettings.php index 49198a62b70a157f4f7d986e5ee0e9201f9b0795..f9829238af6edef38bb90ea9c6e61962d04c1372 100644 --- a/Modules/LearningModule/classes/class.ilECSLearningModuleSettings.php +++ b/Modules/LearningModule/classes/class.ilECSLearningModuleSettings.php @@ -1,32 +1,30 @@ - -* $Id: class.ilObjCourseGUI.php 31646 2011-11-14 11:39:37Z jluetzen $ -* -* @ingroup Modules/LearningModule -*/ -class ilECSLearningModuleSettings extends ilECSObjectSettings -{ - protected function getECSObjectType() - { - return '/campusconnect/learningmodules'; - } - - protected function buildJson(ilECSSetting $a_server) - { - $json = $this->getJsonCore('application/ecs-learningmodule'); - - $json->availability = $this->content_obj->getOfflineStatus() ? 'offline' : 'online'; - - return $json; - } -} - -?> \ No newline at end of file + +* $Id: class.ilObjCourseGUI.php 31646 2011-11-14 11:39:37Z jluetzen $ +* +* @ingroup Modules/LearningModule +*/ +class ilECSLearningModuleSettings extends ilECSObjectSettings +{ + protected function getECSObjectType() + { + return '/campusconnect/learningmodules'; + } + + protected function buildJson(ilECSSetting $a_server) + { + $json = $this->getJsonCore('application/ecs-learningmodule'); + + $json->availability = $this->content_obj->getOfflineStatus() ? 'offline' : 'online'; + + return $json; + } +} diff --git a/Modules/LearningModule/classes/class.ilEditClipboard.php b/Modules/LearningModule/classes/class.ilEditClipboard.php index 6b73d92b3c6a4466d58eb7b4e298b2721d4bfc1f..7646afc757cb52a7e316adb43878df6fb3749561 100755 --- a/Modules/LearningModule/classes/class.ilEditClipboard.php +++ b/Modules/LearningModule/classes/class.ilEditClipboard.php @@ -1,24 +1,24 @@ $a_action); - } + public static function setAction($a_action) + { + $_SESSION["ilEditClipboard"] = array("action" => $a_action); + } - static function getAction() - { - if (isset($_SESSION["ilEditClipboard"])) - { - return $_SESSION["ilEditClipboard"]["action"]; - } - else - { - return false; - } - } + public static function getAction() + { + if (isset($_SESSION["ilEditClipboard"])) { + return $_SESSION["ilEditClipboard"]["action"]; + } else { + return false; + } + } - static function getContentObjectId() - { - if (isset($_SESSION["ilEditClipboard"])) - { - return $_SESSION["ilEditClipboard"]["id"]; - } - } + public static function getContentObjectId() + { + if (isset($_SESSION["ilEditClipboard"])) { + return $_SESSION["ilEditClipboard"]["id"]; + } + } - static function storeContentObject($a_type, $a_id, $a_action = "cut") - { - $_SESSION["ilEditClipboard"] = array("type" => $a_type, - "id" => $a_id, "action" => $a_action); - } + public static function storeContentObject($a_type, $a_id, $a_action = "cut") + { + $_SESSION["ilEditClipboard"] = array("type" => $a_type, + "id" => $a_id, "action" => $a_action); + } - static function clear() - { - unset($_SESSION["ilEditClipboard"]); - } + public static function clear() + { + unset($_SESSION["ilEditClipboard"]); + } } -?> diff --git a/Modules/LearningModule/classes/class.ilExportIDTableGUI.php b/Modules/LearningModule/classes/class.ilExportIDTableGUI.php index 5fec142277ba3c144befe37a3a71c986b6041b9e..bea52f17e55c2d8523dc4b58616b06d0c1aa6b14 100644 --- a/Modules/LearningModule/classes/class.ilExportIDTableGUI.php +++ b/Modules/LearningModule/classes/class.ilExportIDTableGUI.php @@ -13,134 +13,148 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilExportIDTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; - - var $online_help_mode = false; - - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_validation = false, - $a_oh_mode = false) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - $this->setOnlineHelpMode($a_oh_mode); - $this->setId("lm_expids"); - $this->validation = $a_validation; - - parent::__construct($a_parent_obj, $a_parent_cmd); - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - - if ($this->getOnlineHelpMode()) - { - $this->setData(ilStructureObject::getChapterList($this->parent_obj->object->getId())); - $this->cnt_exp_ids = ilLMPageObject::getDuplicateExportIDs( - $this->parent_obj->object->getId(), "st"); - } - else - { - $this->setData(ilLMPageObject::getPageList($this->parent_obj->object->getId())); - $this->cnt_exp_ids = ilLMPageObject::getDuplicateExportIDs( - $this->parent_obj->object->getId()); - } - - $this->setTitle($lng->txt("cont_html_export_ids")); - - $this->addColumn($this->lng->txt("pg"), "title"); - $this->addColumn($this->lng->txt("cont_export_id")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.export_id_row.html", "Modules/LearningModule"); - $this->setDefaultOrderField("title"); - $this->setDefaultOrderDirection("asc"); - - $this->addCommandButton("saveExportIDs", $lng->txt("save")); - } - - /** - * Set online help mode - * - * @param bool $a_val online help mode - */ - function setOnlineHelpMode($a_val) - { - $this->online_help_mode = $a_val; - } - - /** - * Get online help mode - * - * @return bool online help mode - */ - function getOnlineHelpMode() - { - return $this->online_help_mode; - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - $this->tpl->setVariable("VAL_TITLE", $a_set["title"]); - $this->tpl->setVariable("PAGE_ID", $a_set["obj_id"]); - - $exp_id = ilLMPageObject::getExportId( - $this->parent_obj->object->getId(), $a_set["obj_id"], $a_set["type"]); - - if ($this->validation) - { - if (!preg_match("/^[a-zA-Z_]*$/", - trim($_POST["exportid"][$a_set["obj_id"]]))) - { - // @todo: move to style - $this->tpl->setVariable("STYLE", - " style='background-color: #FCEAEA;' "); - $this->tpl->setVariable("ALERT_IMG", - ilUtil::img(ilUtil::getImagePath("icon_alert.svg"), - $lng->txt("alert")) - ); - } - $this->tpl->setVariable("EXPORT_ID", - ilUtil::prepareFormOutput( - ilUtil::stripSlashes($_POST["exportid"][$a_set["obj_id"]]))); - } - else - { - $this->tpl->setVariable("EXPORT_ID", - ilUtil::prepareFormOutput($exp_id)); - } - - if ($this->cnt_exp_ids[$exp_id] > 1) - { - $this->tpl->setVariable("ITEM_ADD_TXT", - $lng->txt("cont_exp_id_used_multiple")); - $this->tpl->setVariable("ALERT_IMG", - ilUtil::img(ilUtil::getImagePath("icon_alert.svg"), - $lng->txt("alert")) - ); - if (!$this->dup_info_given) - { - ilUtil::sendInfo($lng->txt("content_some_export_ids_multiple_times")); - $this->dup_info_given = true; - } - } - } - + /** + * @var ilAccessHandler + */ + protected $access; + + public $online_help_mode = false; + + + /** + * Constructor + */ + public function __construct( + $a_parent_obj, + $a_parent_cmd, + $a_validation = false, + $a_oh_mode = false + ) { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + $this->setOnlineHelpMode($a_oh_mode); + $this->setId("lm_expids"); + $this->validation = $a_validation; + + parent::__construct($a_parent_obj, $a_parent_cmd); + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + + if ($this->getOnlineHelpMode()) { + $this->setData(ilStructureObject::getChapterList($this->parent_obj->object->getId())); + $this->cnt_exp_ids = ilLMPageObject::getDuplicateExportIDs( + $this->parent_obj->object->getId(), + "st" + ); + } else { + $this->setData(ilLMPageObject::getPageList($this->parent_obj->object->getId())); + $this->cnt_exp_ids = ilLMPageObject::getDuplicateExportIDs( + $this->parent_obj->object->getId() + ); + } + + $this->setTitle($lng->txt("cont_html_export_ids")); + + $this->addColumn($this->lng->txt("pg"), "title"); + $this->addColumn($this->lng->txt("cont_export_id")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.export_id_row.html", "Modules/LearningModule"); + $this->setDefaultOrderField("title"); + $this->setDefaultOrderDirection("asc"); + + $this->addCommandButton("saveExportIDs", $lng->txt("save")); + } + + /** + * Set online help mode + * + * @param bool $a_val online help mode + */ + public function setOnlineHelpMode($a_val) + { + $this->online_help_mode = $a_val; + } + + /** + * Get online help mode + * + * @return bool online help mode + */ + public function getOnlineHelpMode() + { + return $this->online_help_mode; + } + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + + $this->tpl->setVariable("VAL_TITLE", $a_set["title"]); + $this->tpl->setVariable("PAGE_ID", $a_set["obj_id"]); + + $exp_id = ilLMPageObject::getExportId( + $this->parent_obj->object->getId(), + $a_set["obj_id"], + $a_set["type"] + ); + + if ($this->validation) { + if (!preg_match( + "/^[a-zA-Z_]*$/", + trim($_POST["exportid"][$a_set["obj_id"]]) + )) { + // @todo: move to style + $this->tpl->setVariable( + "STYLE", + " style='background-color: #FCEAEA;' " + ); + $this->tpl->setVariable( + "ALERT_IMG", + ilUtil::img( + ilUtil::getImagePath("icon_alert.svg"), + $lng->txt("alert") + ) + ); + } + $this->tpl->setVariable( + "EXPORT_ID", + ilUtil::prepareFormOutput( + ilUtil::stripSlashes($_POST["exportid"][$a_set["obj_id"]]) + ) + ); + } else { + $this->tpl->setVariable( + "EXPORT_ID", + ilUtil::prepareFormOutput($exp_id) + ); + } + + if ($this->cnt_exp_ids[$exp_id] > 1) { + $this->tpl->setVariable( + "ITEM_ADD_TXT", + $lng->txt("cont_exp_id_used_multiple") + ); + $this->tpl->setVariable( + "ALERT_IMG", + ilUtil::img( + ilUtil::getImagePath("icon_alert.svg"), + $lng->txt("alert") + ) + ); + if (!$this->dup_info_given) { + ilUtil::sendInfo($lng->txt("content_some_export_ids_multiple_times")); + $this->dup_info_given = true; + } + } + } } - -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilHelpMappingTableGUI.php b/Modules/LearningModule/classes/class.ilHelpMappingTableGUI.php index ec58374c474b6a17a59d03df24bace85442e5bc2..501443a96bd26cbcdd41aaa06895509ecd538401 100644 --- a/Modules/LearningModule/classes/class.ilHelpMappingTableGUI.php +++ b/Modules/LearningModule/classes/class.ilHelpMappingTableGUI.php @@ -15,94 +15,89 @@ include_once("./Services/Help/classes/class.ilHelpMapping.php"); */ class ilHelpMappingTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; - - var $online_help_mode = false; - - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_validation = false) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); - - $this->setId("lm_help_map"); - $this->validation = $a_validation; - - parent::__construct($a_parent_obj, $a_parent_cmd); - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - - $this->getChapters(); - - $this->setTitle($lng->txt("help_assign_help_ids")); - - $this->addColumn($this->lng->txt("st"), "title"); - $this->addColumn($this->lng->txt("cont_screen_ids")); - - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.help_map_row.html", "Modules/LearningModule"); - $this->setDefaultOrderField("title"); - $this->setDefaultOrderDirection("asc"); - - $this->addCommandButton("saveHelpMapping", $lng->txt("save")); - } - - /** - * Get chapters - * - * @param - * @return - */ - function getChapters() - { - $hc = ilSession::get("help_chap"); - $lm_tree = $this->parent_obj->object->getTree(); - - if ($hc > 0 && $lm_tree->isInTree($hc)) - { - //$node = $lm_tree->getNodeData($hc); - //$chaps = $lm_tree->getSubTree($node); - $chaps = $lm_tree->getFilteredSubTree($hc, array("pg")); - unset($chaps[0]); - } - else - { - $chaps = ilStructureObject::getChapterList($this->parent_obj->object->getId()); - } - - $this->setData($chaps); - } - - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - $this->tpl->setVariable("VAL_TITLE", $a_set["title"]); - $this->tpl->setVariable("PAGE_ID", $a_set["obj_id"]); - - $screen_ids = ilHelpMapping::getScreenIdsOfChapter($a_set["obj_id"]); - - $this->tpl->setVariable("SCREEN_IDS", - ilUtil::prepareFormOutput(implode($screen_ids, "\n"))); - - } - + /** + * @var ilAccessHandler + */ + protected $access; + + public $online_help_mode = false; + + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_validation = false) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); + + $this->setId("lm_help_map"); + $this->validation = $a_validation; + + parent::__construct($a_parent_obj, $a_parent_cmd); + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + + $this->getChapters(); + + $this->setTitle($lng->txt("help_assign_help_ids")); + + $this->addColumn($this->lng->txt("st"), "title"); + $this->addColumn($this->lng->txt("cont_screen_ids")); + + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.help_map_row.html", "Modules/LearningModule"); + $this->setDefaultOrderField("title"); + $this->setDefaultOrderDirection("asc"); + + $this->addCommandButton("saveHelpMapping", $lng->txt("save")); + } + + /** + * Get chapters + * + * @param + * @return + */ + public function getChapters() + { + $hc = ilSession::get("help_chap"); + $lm_tree = $this->parent_obj->object->getTree(); + + if ($hc > 0 && $lm_tree->isInTree($hc)) { + //$node = $lm_tree->getNodeData($hc); + //$chaps = $lm_tree->getSubTree($node); + $chaps = $lm_tree->getFilteredSubTree($hc, array("pg")); + unset($chaps[0]); + } else { + $chaps = ilStructureObject::getChapterList($this->parent_obj->object->getId()); + } + + $this->setData($chaps); + } + + + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + + $this->tpl->setVariable("VAL_TITLE", $a_set["title"]); + $this->tpl->setVariable("PAGE_ID", $a_set["obj_id"]); + + $screen_ids = ilHelpMapping::getScreenIdsOfChapter($a_set["obj_id"]); + + $this->tpl->setVariable( + "SCREEN_IDS", + ilUtil::prepareFormOutput(implode($screen_ids, "\n")) + ); + } } - -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilHelpTooltipTableGUI.php b/Modules/LearningModule/classes/class.ilHelpTooltipTableGUI.php index cc4a7fa66c96fc672c974e4e45e77e6efd380ffb..b8f8e028eb4f0e63e837e9d92cb6c786b6a57e34 100644 --- a/Modules/LearningModule/classes/class.ilHelpTooltipTableGUI.php +++ b/Modules/LearningModule/classes/class.ilHelpTooltipTableGUI.php @@ -15,62 +15,58 @@ include_once("./Services/Help/classes/class.ilHelpMapping.php"); */ class ilHelpTooltipTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_comp) - { - global $DIC; + + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_comp) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); - $this->setId("lm_help_tooltips"); + $this->setId("lm_help_tooltips"); - parent::__construct($a_parent_obj, $a_parent_cmd); - - include_once("./Services/Help/classes/class.ilHelp.php"); - $this->setData(ilHelp::getAllTooltips($a_comp)); + parent::__construct($a_parent_obj, $a_parent_cmd); + + include_once("./Services/Help/classes/class.ilHelp.php"); + $this->setData(ilHelp::getAllTooltips($a_comp)); - $this->setTitle($lng->txt("help_tooltips")); + $this->setTitle($lng->txt("help_tooltips")); - $this->addColumn("", "", "1px", true); - $this->addColumn($this->lng->txt("help_tooltip_id")); - $this->addColumn($this->lng->txt("help_tt_text")); + $this->addColumn("", "", "1px", true); + $this->addColumn($this->lng->txt("help_tooltip_id")); + $this->addColumn($this->lng->txt("help_tt_text")); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.help_tooltip.html", "Modules/LearningModule"); - $this->setDefaultOrderField("tt_id"); - $this->setDefaultOrderDirection("asc"); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.help_tooltip.html", "Modules/LearningModule"); + $this->setDefaultOrderField("tt_id"); + $this->setDefaultOrderDirection("asc"); - $this->addCommandButton("saveTooltips", $lng->txt("save")); - $this->addMultiCommand("deleteTooltips", $lng->txt("delete")); - } + $this->addCommandButton("saveTooltips", $lng->txt("save")); + $this->addMultiCommand("deleteTooltips", $lng->txt("delete")); + } - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - - $this->tpl->setVariable("ID", $a_set["id"]); - $this->tpl->setVariable("TEXT", ilUtil::prepareFormOutput($a_set["text"])); - $this->tpl->setVariable("TT_ID", ilUtil::prepareFormOutput($a_set["tt_id"])); - - } + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $this->tpl->setVariable("ID", $a_set["id"]); + $this->tpl->setVariable("TEXT", ilUtil::prepareFormOutput($a_set["text"])); + $this->tpl->setVariable("TT_ID", ilUtil::prepareFormOutput($a_set["tt_id"])); + } } - -?> \ No newline at end of file diff --git a/Modules/LearningModule/classes/class.ilLMBlockedUsersTableGUI.php b/Modules/LearningModule/classes/class.ilLMBlockedUsersTableGUI.php index 83129bfa44824be79d271c65876651e53ee7a477..26e25b91c222dacaaa2fb6eb2ccda73165ce3ed7 100644 --- a/Modules/LearningModule/classes/class.ilLMBlockedUsersTableGUI.php +++ b/Modules/LearningModule/classes/class.ilLMBlockedUsersTableGUI.php @@ -5,7 +5,7 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); /** - * TableGUI class for + * TableGUI class for * * @author Alex Killing
".$im_tag." | ". - $lng->txt("cont_lm_default_layout"). - ": ".$lng->txt("cont_layout_".$this->content_object->getLayout()). - " |
".$im_tag." | ". - $lng->txt("cont_layout_".$l).": ".$lng->txt("cont_layout_".$l."_desc"). - " |
" . $im_tag . " | " . + $lng->txt("cont_lm_default_layout") . + ": " . $lng->txt("cont_layout_" . $this->content_object->getLayout()) . + " |
" . $im_tag . " | " . + $lng->txt("cont_layout_" . $l) . ": " . $lng->txt("cont_layout_" . $l . "_desc") . + " |
" . sprintf( + $this->lng->txt("cont_page_activation_on"), + ilDatePresentation::formatDate( + new ilDateTime($act_data["activation_start"], IL_CAL_DATETIME) + ) + ) . + "
"; + } + $mtpl->setVariable("MESSAGE", $m); + //$mtpl->setVariable("SRC_ICON", ilUtil::getImagePath("icon_pg.svg", + // false, "output", $this->offlineMode())); + $mtpl->setVariable( + "ITEM_TITLE", + ilLMObject::_lookupTitle($_GET["obj_id"]) + ); + $this->tpl->setVariable("PAGE_CONTENT", $mtpl->get()); + return $mtpl->get(); + } + + // check if page is out of focus + $focus_mess = ""; + if ($this->focus_id > 0) { + $path = $this->lm_tree->getPathId($page_id); + + // out of focus + if (!in_array($this->focus_id, $path)) { + $mtpl = new ilTemplate( + "tpl.out_of_focus_message.html", + true, + true, + "Modules/LearningModule" + ); + $mtpl->setVariable("MESSAGE", $this->lng->txt("cont_out_of_focus_message")); + $mtpl->setVariable("TXT_SHOW_CONTENT", $this->lng->txt("cont_show_content_after_focus")); + + if ($_GET["focus_return"] == "" || ilObject::_lookupType((int) $_GET["focus_return"], true) != "crs") { + $mtpl->setVariable("TXT_BACK_BEGINNING", $this->lng->txt("cont_to_focus_beginning")); + $this->ctrl->setParameter($this, "obj_id", $this->focus_id); + $mtpl->setVariable("LINK_BACK_TO_BEGINNING", $this->ctrl->getLinkTarget($this, "layout")); + $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); + } else { + $mtpl->setVariable("TXT_BACK_BEGINNING", $this->lng->txt("cont_to_focus_return_crs")); + include_once("./Services/Link/classes/class.ilLink.php"); + $mtpl->setVariable("LINK_BACK_TO_BEGINNING", ilLink::_getLink((int) $_GET["focus_return"])); + } + + $this->ctrl->setParameter($this, "focus_id", ""); + $mtpl->setVariable("LINK_SHOW_CONTENT", $this->ctrl->getLinkTarget($this, "layout")); + $this->ctrl->setParameter($this, "focus_id", $_GET["focus_id"]); + + $focus_mess = $mtpl->get(); + } else { + $sp = $this->getSuccessorPage(); + $path2 = array(); + if ($sp > 0) { + $path2 = $this->lm_tree->getPathId($this->getSuccessorPage()); + } + if ($sp == 0 || !in_array($this->focus_id, $path2)) { + $mtpl = new ilTemplate( + "tpl.out_of_focus_message.html", + true, + true, + "Modules/LearningModule" + ); + $mtpl->setVariable("MESSAGE", $this->lng->txt("cont_out_of_focus_message_last_page")); + $mtpl->setVariable("TXT_SHOW_CONTENT", $this->lng->txt("cont_show_content_after_focus")); + + if ($_GET["focus_return"] == "" || ilObject::_lookupType((int) $_GET["focus_return"], true) != "crs") { + $mtpl->setVariable("TXT_BACK_BEGINNING", $this->lng->txt("cont_to_focus_beginning")); + $this->ctrl->setParameter($this, "obj_id", $this->focus_id); + $mtpl->setVariable("LINK_BACK_TO_BEGINNING", $this->ctrl->getLinkTarget($this, "layout")); + $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); + } else { + $mtpl->setVariable("TXT_BACK_BEGINNING", $this->lng->txt("cont_to_focus_return_crs")); + include_once("./Services/Link/classes/class.ilLink.php"); + $mtpl->setVariable("LINK_BACK_TO_BEGINNING", ilLink::_getLink((int) $_GET["focus_return"])); + } + + $this->ctrl->setParameter($this, "focus_id", ""); + $mtpl->setVariable("LINK_SHOW_CONTENT", $this->ctrl->getLinkTarget($this, "layout")); + $this->ctrl->setParameter($this, "focus_id", $_GET["focus_id"]); + + $focus_mess = $mtpl->get(); + } + } + } + + // no page found + if ($page_id == 0) { + $cont = $this->lng->txt("cont_no_page"); + $this->tpl->setVariable("PAGE_CONTENT", $cont); + return $cont; + } + + + $page_object_gui = $this->getLMPageGUI($page_id); + $this->basicPageGuiInit($page_object_gui); + $page_object = $page_object_gui->getPageObject(); + $page_object->buildDom(); + $page_object->registerOfflineHandler($this); + + $int_links = $page_object->getInternalLinks(); + + + + $page_object_gui->setTemplateOutput(false); + + // Update personal desktop items + $ilUser->setDesktopItemParameters($this->lm->getRefId(), $this->lm->getType(), $page_id); + + // Update course items + include_once './Modules/Course/classes/class.ilCourseLMHistory.php'; + ilCourseLMHistory::_updateLastAccess($ilUser->getId(), $this->lm->getRefId(), $page_id); + + // read link targets + $link_xml = $this->getLinkXML($int_links, $this->getLayoutLinkTargets()); + $link_xml.= $this->getLinkTargetsXML(); + + // get lm page object + $lm_pg_obj = new ilLMPageObject($this->lm, $page_id); + $lm_pg_obj->setLMId($this->lm->getId()); + //$pg_obj->setParentId($this->lm->getId()); + $page_object_gui->setLinkXML($link_xml); + + // determine target frames for internal links + //$pg_frame = $_GET["frame"]; + $page_object_gui->setLinkFrame($_GET["frame"]); + + // page title and tracking (not for header or footer page) + if ($page_id == 0 || ($page_id != $this->lm->getHeaderPage() && + $page_id != $this->lm->getFooterPage())) { + $page_object_gui->setPresentationTitle( + ilLMPageObject::_getPresentationTitle( + $lm_pg_obj->getId(), + $this->lm->getPageHeader(), + $this->lm->isActiveNumbering(), + $this->lm_set->get("time_scheduled_page_activation"), + false, + 0, + $this->lang + ) + ); + + // track access + if ($ilUser->getId() != ANONYMOUS_USER_ID && $page_id != 0 && !$this->offlineMode()) { + $this->getTracker()->trackAccess($page_id); + } + } else { + $page_object_gui->setEnabledPageFocus(false); + $page_object_gui->getPageConfig()->setEnableSelfAssessment(false); + } + + // ADDED FOR CITATION + $page_object_gui->setLinkParams("ref_id=" . $this->lm->getRefId()); + $page_object_gui->setTemplateTargetVar("PAGE_CONTENT"); + $page_object_gui->setSourcecodeDownloadScript($this->getSourcecodeDownloadLink()); + + // syntax style + $this->tpl->setCurrentBlock("SyntaxStyle"); + if (!$this->offlineMode()) { + $this->tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + ilObjStyleSheet::getSyntaxStylePath() + ); + } else { + $this->tpl->setVariable( + "LOCATION_SYNTAX_STYLESHEET", + "syntaxhighlight.css" + ); + } + $this->tpl->parseCurrentBlock(); + + + $ret = $page_object_gui->presentation($page_object_gui->getOutputMode()); + + // process header + if ($this->lm->getHeaderPage() > 0 && + $page_id != $this->lm->getHeaderPage() && + ($page_id == 0 || $page_id != $this->lm->getFooterPage())) { + if (ilLMObject::_exists($this->lm->getHeaderPage())) { + $head = $this->ilPage($a_page_node, $this->lm->getHeaderPage()); + } + } + + // process footer + if ($this->lm->getFooterPage() > 0 && + $page_id != $this->lm->getFooterPage() && + ($page_id == 0 || $page_id != $this->lm->getHeaderPage())) { + if (ilLMObject::_exists($this->lm->getFooterPage())) { + $foot = $this->ilPage($a_page_node, $this->lm->getFooterPage()); + } + } + + // rating + $rating = ""; + if ($this->lm->hasRatingPages() && !$this->offlineMode()) { + include_once("./Services/Rating/classes/class.ilRatingGUI.php"); + $rating_gui = new ilRatingGUI(); + $rating_gui->setObject($this->lm->getId(), "lm", $page_id, "lm"); + $rating_gui->setYourRatingText($this->lng->txt("lm_rate_page")); + + /* + $this->tpl->setVariable("VAL_RATING", $rating->getHTML(false, true, + "il.ExcPeerReview.saveComments(".$a_set["peer_id"].", %rating%)")); + */ + + $this->ctrl->setParameter($this, "pgid", $page_id); + $this->tpl->addOnLoadCode("il.LearningModule.setRatingUrl('" . + $this->ctrl->getLinkTarget($this, "updatePageRating", "", true, false) . + "')"); + $this->ctrl->setParameter($this, "pgid", ""); + + $rating = '".sprintf($this->lng->txt("cont_page_activation_on"), - ilDatePresentation::formatDate(new ilDateTime($act_data["activation_start"],IL_CAL_DATETIME) - )). - "
"; - } - $mtpl->setVariable("MESSAGE", $m); - //$mtpl->setVariable("SRC_ICON", ilUtil::getImagePath("icon_pg.svg", - // false, "output", $this->offlineMode())); - $mtpl->setVariable("ITEM_TITLE", - ilLMObject::_lookupTitle($_GET["obj_id"])); - $this->tpl->setVariable("PAGE_CONTENT", $mtpl->get()); - return $mtpl->get(); - } - - // check if page is out of focus - $focus_mess = ""; - if ($this->focus_id > 0) - { - $path = $this->lm_tree->getPathId($page_id); - - // out of focus - if (!in_array($this->focus_id, $path)) - { - $mtpl = new ilTemplate("tpl.out_of_focus_message.html", true, true, - "Modules/LearningModule"); - $mtpl->setVariable("MESSAGE", $this->lng->txt("cont_out_of_focus_message")); - $mtpl->setVariable("TXT_SHOW_CONTENT", $this->lng->txt("cont_show_content_after_focus")); - - if ($_GET["focus_return"] == "" || ilObject::_lookupType((int) $_GET["focus_return"], true) != "crs") - { - $mtpl->setVariable("TXT_BACK_BEGINNING", $this->lng->txt("cont_to_focus_beginning")); - $this->ctrl->setParameter($this, "obj_id", $this->focus_id); - $mtpl->setVariable("LINK_BACK_TO_BEGINNING", $this->ctrl->getLinkTarget($this, "layout")); - $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); - } - else - { - $mtpl->setVariable("TXT_BACK_BEGINNING", $this->lng->txt("cont_to_focus_return_crs")); - include_once("./Services/Link/classes/class.ilLink.php"); - $mtpl->setVariable("LINK_BACK_TO_BEGINNING", ilLink::_getLink((int) $_GET["focus_return"])); - } - - $this->ctrl->setParameter($this, "focus_id", ""); - $mtpl->setVariable("LINK_SHOW_CONTENT", $this->ctrl->getLinkTarget($this, "layout")); - $this->ctrl->setParameter($this, "focus_id", $_GET["focus_id"]); - - $focus_mess = $mtpl->get(); - } - else - { - $sp = $this->getSuccessorPage(); - $path2 = array(); - if ($sp > 0) - { - $path2 = $this->lm_tree->getPathId($this->getSuccessorPage()); - } - if ($sp == 0 || !in_array($this->focus_id, $path2)) - { - $mtpl = new ilTemplate("tpl.out_of_focus_message.html", true, true, - "Modules/LearningModule"); - $mtpl->setVariable("MESSAGE", $this->lng->txt("cont_out_of_focus_message_last_page")); - $mtpl->setVariable("TXT_SHOW_CONTENT", $this->lng->txt("cont_show_content_after_focus")); - - if ($_GET["focus_return"] == "" || ilObject::_lookupType((int) $_GET["focus_return"], true) != "crs") - { - $mtpl->setVariable("TXT_BACK_BEGINNING", $this->lng->txt("cont_to_focus_beginning")); - $this->ctrl->setParameter($this, "obj_id", $this->focus_id); - $mtpl->setVariable("LINK_BACK_TO_BEGINNING", $this->ctrl->getLinkTarget($this, "layout")); - $this->ctrl->setParameter($this, "obj_id", $_GET["obj_id"]); - } - else - { - $mtpl->setVariable("TXT_BACK_BEGINNING", $this->lng->txt("cont_to_focus_return_crs")); - include_once("./Services/Link/classes/class.ilLink.php"); - $mtpl->setVariable("LINK_BACK_TO_BEGINNING", ilLink::_getLink((int) $_GET["focus_return"])); - } - - $this->ctrl->setParameter($this, "focus_id", ""); - $mtpl->setVariable("LINK_SHOW_CONTENT", $this->ctrl->getLinkTarget($this, "layout")); - $this->ctrl->setParameter($this, "focus_id", $_GET["focus_id"]); - - $focus_mess = $mtpl->get(); - } - } - } - - // no page found - if ($page_id == 0) - { - $cont = $this->lng->txt("cont_no_page"); - $this->tpl->setVariable("PAGE_CONTENT", $cont); - return $cont; - } - - - $page_object_gui = $this->getLMPageGUI($page_id); - $this->basicPageGuiInit($page_object_gui); - $page_object = $page_object_gui->getPageObject(); - $page_object->buildDom(); - $page_object->registerOfflineHandler($this); - - $int_links = $page_object->getInternalLinks(); - - - - $page_object_gui->setTemplateOutput(false); - - // Update personal desktop items - $ilUser->setDesktopItemParameters($this->lm->getRefId(), $this->lm->getType(), $page_id); - - // Update course items - include_once './Modules/Course/classes/class.ilCourseLMHistory.php'; - ilCourseLMHistory::_updateLastAccess($ilUser->getId(),$this->lm->getRefId(),$page_id); - - // read link targets - $link_xml = $this->getLinkXML($int_links, $this->getLayoutLinkTargets()); - $link_xml.= $this->getLinkTargetsXML(); - - // get lm page object - $lm_pg_obj = new ilLMPageObject($this->lm, $page_id); - $lm_pg_obj->setLMId($this->lm->getId()); - //$pg_obj->setParentId($this->lm->getId()); - $page_object_gui->setLinkXML($link_xml); - - // determine target frames for internal links - //$pg_frame = $_GET["frame"]; - $page_object_gui->setLinkFrame($_GET["frame"]); - - // page title and tracking (not for header or footer page) - if ($page_id == 0 || ($page_id != $this->lm->getHeaderPage() && - $page_id != $this->lm->getFooterPage())) - { - $page_object_gui->setPresentationTitle( - ilLMPageObject::_getPresentationTitle($lm_pg_obj->getId(), - $this->lm->getPageHeader(), $this->lm->isActiveNumbering(), - $this->lm_set->get("time_scheduled_page_activation"), false, 0, $this->lang)); - - // track access - if ($ilUser->getId() != ANONYMOUS_USER_ID && $page_id != 0 && !$this->offlineMode()) - { - $this->getTracker()->trackAccess($page_id); - } - } - else - { - $page_object_gui->setEnabledPageFocus(false); - $page_object_gui->getPageConfig()->setEnableSelfAssessment(false); - } - - // ADDED FOR CITATION - $page_object_gui->setLinkParams("ref_id=".$this->lm->getRefId()); - $page_object_gui->setTemplateTargetVar("PAGE_CONTENT"); - $page_object_gui->setSourcecodeDownloadScript($this->getSourcecodeDownloadLink()); - - // syntax style - $this->tpl->setCurrentBlock("SyntaxStyle"); - if (!$this->offlineMode()) - { - $this->tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - ilObjStyleSheet::getSyntaxStylePath()); - } - else - { - $this->tpl->setVariable("LOCATION_SYNTAX_STYLESHEET", - "syntaxhighlight.css"); - } - $this->tpl->parseCurrentBlock(); - - - $ret = $page_object_gui->presentation($page_object_gui->getOutputMode()); - - // process header - if ($this->lm->getHeaderPage() > 0 && - $page_id != $this->lm->getHeaderPage() && - ($page_id == 0 || $page_id != $this->lm->getFooterPage())) - { - if (ilLMObject::_exists($this->lm->getHeaderPage())) - { - $head = $this->ilPage($a_page_node, $this->lm->getHeaderPage()); - } - } - - // process footer - if ($this->lm->getFooterPage() > 0 && - $page_id != $this->lm->getFooterPage() && - ($page_id == 0 || $page_id != $this->lm->getHeaderPage())) - { - if (ilLMObject::_exists($this->lm->getFooterPage())) - { - $foot = $this->ilPage($a_page_node, $this->lm->getFooterPage()); - } - } - - // rating - $rating = ""; - if($this->lm->hasRatingPages() && !$this->offlineMode()) - { - include_once("./Services/Rating/classes/class.ilRatingGUI.php"); - $rating_gui = new ilRatingGUI(); - $rating_gui->setObject($this->lm->getId(), "lm", $page_id, "lm"); - $rating_gui->setYourRatingText($this->lng->txt("lm_rate_page")); - - /* - $this->tpl->setVariable("VAL_RATING", $rating->getHTML(false, true, - "il.ExcPeerReview.saveComments(".$a_set["peer_id"].", %rating%)")); - */ - - $this->ctrl->setParameter($this, "pgid", $page_id); - $this->tpl->addOnLoadCode("il.LearningModule.setRatingUrl('". - $this->ctrl->getLinkTarget($this, "updatePageRating", "", true, false). - "')"); - $this->ctrl->setParameter($this, "pgid", ""); - - $rating = '".$im_tag." | ". - $lng->txt("cont_lm_default_layout"). - ": ".$lng->txt("cont_layout_".$a_def_option). - " |
". - $im_tag." | ".$lng->txt("cont_layout_".$l).": ". - $lng->txt("cont_layout_".$l."_desc")." |
" . $im_tag . " | " . + $lng->txt("cont_lm_default_layout") . + ": " . $lng->txt("cont_layout_" . $a_def_option) . + " |
" . + $im_tag . " | " . $lng->txt("cont_layout_" . $l) . ": " . + $lng->txt("cont_layout_" . $l . "_desc") . " |
'.$feed_icon_html.'
'; - } - - $tpl->setContent($feed_icon_html.$ctpl->get()); - } - - /** - * Convert file object - * - * @param - * @return - */ - function convertFileObject() - { - $ilCtrl = $this->ctrl; - - $this->checkPermission("write"); - - $this->mcst_item = new ilNewsItem($_GET["item_id"]); - include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); - $mob = new ilObjMediaObject($this->mcst_item->getMobId()); - - $target_purpose = ilUtil::stripSlashes($_POST["target_purpose"]); - $target_format = ilUtil::stripSlashes($_POST["target_format"]); - - try - { - include_once("./Services/MediaObjects/classes/class.ilFFmpeg.php"); - $med = $mob->getMediaItem("Standard"); - $mob_file = ilObjMediaObject::_getDirectory($mob->getId())."/".$med->getLocation(); - $new_file = ilFFmpeg::convert($mob_file, $target_format); - $ret = ilFFmpeg::getLastReturnValues(); - $pi = pathinfo($new_file); - $med = $mob->getMediaItem($target_purpose); - if (!is_object($med)) - { - $med = new ilMediaItem(); - $med->setMobId($mob->getId()); - $mob->addMediaItem($med); - $mob->update(); - $med->setPurpose($target_purpose); - } - $med->setFormat($target_format); - $med->setLocation($pi["basename"]); - $med->setLocationType("LocalFile"); - $med->update(); - - $add = (is_array($ret) && count($ret) > 0) - ? "' . $feed_icon_html . '
'; + } + + $tpl->setContent($feed_icon_html . $ctpl->get()); + } + + /** + * Convert file object + * + * @param + * @return + */ + public function convertFileObject() + { + $ilCtrl = $this->ctrl; + + $this->checkPermission("write"); + + $this->mcst_item = new ilNewsItem($_GET["item_id"]); + include_once("./Services/MediaObjects/classes/class.ilObjMediaObjectGUI.php"); + $mob = new ilObjMediaObject($this->mcst_item->getMobId()); + + $target_purpose = ilUtil::stripSlashes($_POST["target_purpose"]); + $target_format = ilUtil::stripSlashes($_POST["target_format"]); + + try { + include_once("./Services/MediaObjects/classes/class.ilFFmpeg.php"); + $med = $mob->getMediaItem("Standard"); + $mob_file = ilObjMediaObject::_getDirectory($mob->getId()) . "/" . $med->getLocation(); + $new_file = ilFFmpeg::convert($mob_file, $target_format); + $ret = ilFFmpeg::getLastReturnValues(); + $pi = pathinfo($new_file); + $med = $mob->getMediaItem($target_purpose); + if (!is_object($med)) { + $med = new ilMediaItem(); + $med->setMobId($mob->getId()); + $mob->addMediaItem($med); + $mob->update(); + $med->setPurpose($target_purpose); + } + $med->setFormat($target_format); + $med->setLocation($pi["basename"]); + $med->setLocationType("LocalFile"); + $med->update(); + + $add = (is_array($ret) && count($ret) > 0) + ? "" . sprintf($lng->txt("prtf_exercise_submitted_info"), - ilDatePresentation::formatDate(new ilDateTime($submitted["ts"], IL_CAL_DATETIME)), - "") . "
"; - $buttons[] = $ui->factory()->button()->standard($lng->txt("prtf_download_submission"), $dl_link); - } - - ilDatePresentation::setUseRelativeDates($rel); - $info_arr["submitted_date"] = ilDatePresentation::formatDate(new ilDateTime($submitted["ts"], IL_CAL_DATETIME)); - $info_arr["submitted"] = true; - if ($submitted["ts"] == "") - { - $info_arr["submitted"] = false; - } - } + $text .= "" . sprintf( + $lng->txt("prtf_exercise_submitted_info"), + ilDatePresentation::formatDate(new ilDateTime($submitted["ts"], IL_CAL_DATETIME)), + "" + ) . "
"; + $buttons[] = $ui->factory()->button()->standard($lng->txt("prtf_download_submission"), $dl_link); + } + + ilDatePresentation::setUseRelativeDates($rel); + $info_arr["submitted_date"] = ilDatePresentation::formatDate(new ilDateTime($submitted["ts"], IL_CAL_DATETIME)); + $info_arr["submitted"] = true; + if ($submitted["ts"] == "") { + $info_arr["submitted"] = false; + } + } - // work instructions incl. files - - $tooltip = ""; + // work instructions incl. files + + $tooltip = ""; - $inst = $ass->getInstruction(); - if($inst) - { - $tooltip .= nl2br($inst); - } + $inst = $ass->getInstruction(); + if ($inst) { + $tooltip .= nl2br($inst); + } - $ass_files = $ass->getFiles(); - if (!$as_array) - { - if (count($ass_files) > 0) - { - if ($tooltip) - { - $tooltip .= "$error_message
"); - } - if ($show_questiontext) - { - $this->outQuestionText($template); - } - $template->parseCurrentBlock(); - return $template->get(); - } + if ($rowobj->other) { + $tplrow->setCurrentBlock("row_other"); + $tplrow->setVariable("QUESTION_ID", $this->object->getId()); + $tplrow->setVariable("ROW", $i); + if (is_array($working_data)) { + foreach ($working_data as $data) { + if ($data["rowvalue"] == $i) { + $tplrow->setVariable("VALUE_OTHER", ilUtil::prepareFormOutput($data['textanswer'])); + } + } + } + $tplrow->parseCurrentBlock(); + } + $tplrow->setVariable("TEXT_ROW", ilUtil::prepareFormOutput($rowobj->title)); + $tplrow->setVariable("ROWCLASS", $rowclass[$i % 2]); + if ($this->object->getRowSeparators() == 1) { + if ($i < $this->object->getRowCount() - 1) { + $tplrow->setVariable("STYLE", " style=\"border-bottom: 1px solid $bordercolor!important\""); + } + } + $template->setCurrentBlock("matrix_row"); + $template->setVariable("ROW", $tplrow->get()); + $template->parseCurrentBlock(); + } + + if ($question_title) { + $template->setVariable("QUESTION_TITLE", ilUtil::prepareFormOutput($this->object->getTitle())); + } + $template->setCurrentBlock("question_data_matrix"); + if (strcmp($error_message, "") != 0) { + $template->setVariable("ERROR_MESSAGE", "$error_message
"); + } + if ($show_questiontext) { + $this->outQuestionText($template); + } + $template->parseCurrentBlock(); + return $template->get(); + } } - -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyMetricQuestion.php b/Modules/SurveyQuestionPool/classes/class.SurveyMetricQuestion.php index d61f300650a208bc44a7768f7438e6894ada9695..da2ebf9e81b49b85e646ef86f603b018a3aaf883 100755 --- a/Modules/SurveyQuestionPool/classes/class.SurveyMetricQuestion.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyMetricQuestion.php @@ -34,647 +34,609 @@ include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; * @extends SurveyQuestion * @ingroup ModulesSurveyQuestionPool */ -class SurveyMetricQuestion extends SurveyQuestion +class SurveyMetricQuestion extends SurveyQuestion { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - const SUBTYPE_NON_RATIO = 3; - const SUBTYPE_RATIO_NON_ABSOLUTE = 4; - const SUBTYPE_RATIO_ABSOLUTE = 5; - -/** -* Question subtype -* -* A question subtype (Multiple choice single response or multiple choice multiple response) -* -* @var integer -*/ - var $subtype; + const SUBTYPE_NON_RATIO = 3; + const SUBTYPE_RATIO_NON_ABSOLUTE = 4; + const SUBTYPE_RATIO_ABSOLUTE = 5; + + /** + * Question subtype + * + * A question subtype (Multiple choice single response or multiple choice multiple response) + * + * @var integer + */ + public $subtype; -/** -* The minimum value for the metric question -* -* @var double -*/ - var $minimum; + /** + * The minimum value for the metric question + * + * @var double + */ + public $minimum; -/** -* The maximum value for the metric question -* -* @var double -*/ - var $maximum; + /** + * The maximum value for the metric question + * + * @var double + */ + public $maximum; -/** -* SurveyMetricQuestion constructor -* -* The constructor takes possible arguments an creates an instance of the SurveyMetricQuestion object. -* -* @param string $title A title string to describe the question -* @param string $description A description string to describe the question -* @param string $author A string containing the name of the questions author -* @param integer $owner A numerical ID to identify the owner/creator -* @access public -*/ - function __construct($title = "", $description = "", $author = "", $questiontext = "", $owner = -1, $subtype = self::SUBTYPE_NON_RATIO) - { - global $DIC; + /** + * SurveyMetricQuestion constructor + * + * The constructor takes possible arguments an creates an instance of the SurveyMetricQuestion object. + * + * @param string $title A title string to describe the question + * @param string $description A description string to describe the question + * @param string $author A string containing the name of the questions author + * @param integer $owner A numerical ID to identify the owner/creator + * @access public + */ + public function __construct($title = "", $description = "", $author = "", $questiontext = "", $owner = -1, $subtype = self::SUBTYPE_NON_RATIO) + { + global $DIC; - $this->db = $DIC->database(); - parent::__construct($title, $description, $author, $questiontext, $owner); - - $this->subtype = $subtype; - $this->minimum = ""; - $this->maximum = ""; - } - -/** -* Sets the question subtype -* -* @param integer $subtype The question subtype -* @access public -* @see $subtype -*/ - function setSubtype($subtype = self::SUBTYPE_NON_RATIO) - { - $this->subtype = $subtype; - } + $this->db = $DIC->database(); + parent::__construct($title, $description, $author, $questiontext, $owner); + + $this->subtype = $subtype; + $this->minimum = ""; + $this->maximum = ""; + } + + /** + * Sets the question subtype + * + * @param integer $subtype The question subtype + * @access public + * @see $subtype + */ + public function setSubtype($subtype = self::SUBTYPE_NON_RATIO) + { + $this->subtype = $subtype; + } -/** -* Sets the minimum value -* -* @param double $minimum The minimum value -* @access public -* @see $minimum -*/ - function setMinimum($minimum = 0) - { - if($minimum !== NULL) - { - $minimum = (float)$minimum; - } - if(!$minimum) - { - $minimum = NULL; - } - $this->minimum = $minimum; - } + /** + * Sets the minimum value + * + * @param double $minimum The minimum value + * @access public + * @see $minimum + */ + public function setMinimum($minimum = 0) + { + if ($minimum !== null) { + $minimum = (float) $minimum; + } + if (!$minimum) { + $minimum = null; + } + $this->minimum = $minimum; + } -/** -* Sets the maximum value -* -* @param double $maximum The maximum value -* @access public -* @see $maximum -*/ - function setMaximum($maximum = "") - { - if($maximum !== NULL) - { - $maximum = (float)$maximum; - } - if(!$maximum) - { - $maximum = NULL; - } - $this->maximum = $maximum; - } + /** + * Sets the maximum value + * + * @param double $maximum The maximum value + * @access public + * @see $maximum + */ + public function setMaximum($maximum = "") + { + if ($maximum !== null) { + $maximum = (float) $maximum; + } + if (!$maximum) { + $maximum = null; + } + $this->maximum = $maximum; + } -/** -* Gets the question subtype -* -* @return integer The question subtype -* @access public -* @see $subtype -*/ - function getSubtype() - { - return $this->subtype; - } - -/** -* Returns the minimum value of the question -* -* @return double The minimum value of the question -* @access public -* @see $minimum -*/ - function getMinimum() - { - if ((strlen($this->minimum) == 0) && ($this->getSubtype() > 3)) - { - $this->minimum = 0; - } - return (strlen($this->minimum)) ? $this->minimum : NULL; - } - -/** -* Returns the maximum value of the question -* -* @return double The maximum value of the question -* @access public -* @see $maximum -*/ - function getMaximum() - { - return (strlen($this->maximum)) ? $this->maximum : NULL; - } - - /** - * Returns the question data fields from the database - * - * @param integer $id The question ID from the database - * @return array Array containing the question fields and data from the database - * @access public - */ - function getQuestionDataArray($id) - { - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT svy_question.*, " . $this->getAdditionalTableName() . ".* FROM svy_question, " . $this->getAdditionalTableName() . " WHERE svy_question.question_id = %s AND svy_question.question_id = " . $this->getAdditionalTableName() . ".question_fi", - array('integer'), - array($id) - ); - if ($result->numRows() == 1) - { - return $ilDB->fetchAssoc($result); - } - else - { - return array(); - } - } - -/** -* Loads a SurveyMetricQuestion object from the database -* -* @param integer $id The database id of the metric survey question -* @access public -*/ - function loadFromDb($id) - { - $ilDB = $this->db; + /** + * Gets the question subtype + * + * @return integer The question subtype + * @access public + * @see $subtype + */ + public function getSubtype() + { + return $this->subtype; + } + + /** + * Returns the minimum value of the question + * + * @return double The minimum value of the question + * @access public + * @see $minimum + */ + public function getMinimum() + { + if ((strlen($this->minimum) == 0) && ($this->getSubtype() > 3)) { + $this->minimum = 0; + } + return (strlen($this->minimum)) ? $this->minimum : null; + } + + /** + * Returns the maximum value of the question + * + * @return double The maximum value of the question + * @access public + * @see $maximum + */ + public function getMaximum() + { + return (strlen($this->maximum)) ? $this->maximum : null; + } + + /** + * Returns the question data fields from the database + * + * @param integer $id The question ID from the database + * @return array Array containing the question fields and data from the database + * @access public + */ + public function getQuestionDataArray($id) + { + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT svy_question.*, " . $this->getAdditionalTableName() . ".* FROM svy_question, " . $this->getAdditionalTableName() . " WHERE svy_question.question_id = %s AND svy_question.question_id = " . $this->getAdditionalTableName() . ".question_fi", + array('integer'), + array($id) + ); + if ($result->numRows() == 1) { + return $ilDB->fetchAssoc($result); + } else { + return array(); + } + } + + /** + * Loads a SurveyMetricQuestion object from the database + * + * @param integer $id The database id of the metric survey question + * @access public + */ + public function loadFromDb($id) + { + $ilDB = $this->db; - $result = $ilDB->queryF("SELECT svy_question.*, " . $this->getAdditionalTableName() . ".* FROM svy_question LEFT JOIN " . $this->getAdditionalTableName() . " ON " . $this->getAdditionalTableName() . ".question_fi = svy_question.question_id WHERE svy_question.question_id = %s", - array('integer'), - array($id) - ); - if ($result->numRows() == 1) - { - $data = $ilDB->fetchAssoc($result); - $this->setId($data["question_id"]); - $this->setTitle($data["title"]); - $this->setDescription($data["description"]); - $this->setObjId($data["obj_fi"]); - $this->setAuthor($data["author"]); - $this->setOwner($data["owner_fi"]); - $this->label = $data['label']; - include_once("./Services/RTE/classes/class.ilRTE.php"); - $this->setQuestiontext(ilRTE::_replaceMediaObjectImageSrc($data["questiontext"], 1)); - $this->setObligatory($data["obligatory"]); - $this->setComplete($data["complete"]); - $this->setOriginalId($data["original_id"]); - $this->setSubtype($data["subtype"]); + $result = $ilDB->queryF( + "SELECT svy_question.*, " . $this->getAdditionalTableName() . ".* FROM svy_question LEFT JOIN " . $this->getAdditionalTableName() . " ON " . $this->getAdditionalTableName() . ".question_fi = svy_question.question_id WHERE svy_question.question_id = %s", + array('integer'), + array($id) + ); + if ($result->numRows() == 1) { + $data = $ilDB->fetchAssoc($result); + $this->setId($data["question_id"]); + $this->setTitle($data["title"]); + $this->setDescription($data["description"]); + $this->setObjId($data["obj_fi"]); + $this->setAuthor($data["author"]); + $this->setOwner($data["owner_fi"]); + $this->label = $data['label']; + include_once("./Services/RTE/classes/class.ilRTE.php"); + $this->setQuestiontext(ilRTE::_replaceMediaObjectImageSrc($data["questiontext"], 1)); + $this->setObligatory($data["obligatory"]); + $this->setComplete($data["complete"]); + $this->setOriginalId($data["original_id"]); + $this->setSubtype($data["subtype"]); - $result = $ilDB->queryF("SELECT svy_variable.* FROM svy_variable WHERE svy_variable.question_fi = %s", - array('integer'), - array($id) - ); - if ($result->numRows() > 0) - { - if ($data = $ilDB->fetchAssoc($result)) - { - $this->minimum = $data["value1"]; - if (($data["value2"] < 0) or (strcmp($data["value2"], "") == 0)) - { - $this->maximum = ""; - } - else - { - $this->maximum = $data["value2"]; - } - } - } - } - parent::loadFromDb($id); - } + $result = $ilDB->queryF( + "SELECT svy_variable.* FROM svy_variable WHERE svy_variable.question_fi = %s", + array('integer'), + array($id) + ); + if ($result->numRows() > 0) { + if ($data = $ilDB->fetchAssoc($result)) { + $this->minimum = $data["value1"]; + if (($data["value2"] < 0) or (strcmp($data["value2"], "") == 0)) { + $this->maximum = ""; + } else { + $this->maximum = $data["value2"]; + } + } + } + } + parent::loadFromDb($id); + } -/** -* Returns true if the question is complete for use -* -* @result boolean True if the question is complete for use, otherwise false -* @access public -*/ - function isComplete() - { - if ( - strlen($this->getTitle()) && - strlen($this->getAuthor()) && - strlen($this->getQuestiontext()) - ) - { - return 1; - } - else - { - return 0; - } - } - -/** -* Saves a SurveyMetricQuestion object to a database -* -* @access public -*/ - function saveToDb($original_id = "") - { - $ilDB = $this->db; + /** + * Returns true if the question is complete for use + * + * @result boolean True if the question is complete for use, otherwise false + * @access public + */ + public function isComplete() + { + if ( + strlen($this->getTitle()) && + strlen($this->getAuthor()) && + strlen($this->getQuestiontext()) + ) { + return 1; + } else { + return 0; + } + } + + /** + * Saves a SurveyMetricQuestion object to a database + * + * @access public + */ + public function saveToDb($original_id = "") + { + $ilDB = $this->db; - $affectedRows = parent::saveToDb($original_id); - if ($affectedRows == 1) - { - $affectedRows = $ilDB->manipulateF("DELETE FROM " . $this->getAdditionalTableName() . " WHERE question_fi = %s", - array('integer'), - array($this->getId()) - ); - $affectedRows = $ilDB->manipulateF("INSERT INTO " . $this->getAdditionalTableName() . " (question_fi, subtype) VALUES (%s, %s)", - array('integer', 'text'), - array($this->getId(), $this->getSubType()) - ); + $affectedRows = parent::saveToDb($original_id); + if ($affectedRows == 1) { + $affectedRows = $ilDB->manipulateF( + "DELETE FROM " . $this->getAdditionalTableName() . " WHERE question_fi = %s", + array('integer'), + array($this->getId()) + ); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO " . $this->getAdditionalTableName() . " (question_fi, subtype) VALUES (%s, %s)", + array('integer', 'text'), + array($this->getId(), $this->getSubType()) + ); - // saving material uris in the database - $this->saveMaterial(); - - // save categories - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_variable WHERE question_fi = %s", - array('integer'), - array($this->getId()) - ); + // saving material uris in the database + $this->saveMaterial(); + + // save categories + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_variable WHERE question_fi = %s", + array('integer'), + array($this->getId()) + ); - if (preg_match("/[\D]/", $this->maximum) or (strcmp($this->maximum, "∞") == 0)) - { - $max = -1; - } - else - { - $max = $this->getMaximum(); - } - $next_id = $ilDB->nextId('svy_variable'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_variable (variable_id, category_fi, question_fi, value1, value2, sequence, tstamp) VALUES (%s, %s, %s, %s, %s, %s, %s)", - array('integer','integer','integer','float','float','integer','integer'), - array($next_id, 0, $this->getId(), $this->getMinimum(), $max, 0, time()) - ); - } - } - - /** - * Returns an xml representation of the question - * - * @return string The xml representation of the question - * @access public - */ - function toXML($a_include_header = TRUE, $obligatory_state = "") - { - include_once("./Services/Xml/classes/class.ilXmlWriter.php"); - $a_xml_writer = new ilXmlWriter; - $a_xml_writer->xmlHeader(); - $this->insertXML($a_xml_writer, $a_include_header, $obligatory_state); - $xml = $a_xml_writer->xmlDumpMem(FALSE); - if (!$a_include_header) - { - $pos = strpos($xml, "?>"); - $xml = substr($xml, $pos + 2); - } - return $xml; - } - - /** - * Adds the question XML to a given XMLWriter object - * - * @param object $a_xml_writer The XMLWriter object - * @param boolean $a_include_header Determines wheather or not the XML should be used - * @access public - */ - function insertXML(&$a_xml_writer, $a_include_header = TRUE) - { - $attrs = array( - "id" => $this->getId(), - "title" => $this->getTitle(), - "type" => $this->getQuestiontype(), - "subtype" => $this->getSubtype(), - "obligatory" => $this->getObligatory() - ); - $a_xml_writer->xmlStartTag("question", $attrs); - - $a_xml_writer->xmlElement("description", NULL, $this->getDescription()); - $a_xml_writer->xmlElement("author", NULL, $this->getAuthor()); - $a_xml_writer->xmlStartTag("questiontext"); - $this->addMaterialTag($a_xml_writer, $this->getQuestiontext()); - $a_xml_writer->xmlEndTag("questiontext"); + if (preg_match("/[\D]/", $this->maximum) or (strcmp($this->maximum, "∞") == 0)) { + $max = -1; + } else { + $max = $this->getMaximum(); + } + $next_id = $ilDB->nextId('svy_variable'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_variable (variable_id, category_fi, question_fi, value1, value2, sequence, tstamp) VALUES (%s, %s, %s, %s, %s, %s, %s)", + array('integer','integer','integer','float','float','integer','integer'), + array($next_id, 0, $this->getId(), $this->getMinimum(), $max, 0, time()) + ); + } + } + + /** + * Returns an xml representation of the question + * + * @return string The xml representation of the question + * @access public + */ + public function toXML($a_include_header = true, $obligatory_state = "") + { + include_once("./Services/Xml/classes/class.ilXmlWriter.php"); + $a_xml_writer = new ilXmlWriter; + $a_xml_writer->xmlHeader(); + $this->insertXML($a_xml_writer, $a_include_header, $obligatory_state); + $xml = $a_xml_writer->xmlDumpMem(false); + if (!$a_include_header) { + $pos = strpos($xml, "?>"); + $xml = substr($xml, $pos + 2); + } + return $xml; + } + + /** + * Adds the question XML to a given XMLWriter object + * + * @param object $a_xml_writer The XMLWriter object + * @param boolean $a_include_header Determines wheather or not the XML should be used + * @access public + */ + public function insertXML(&$a_xml_writer, $a_include_header = true) + { + $attrs = array( + "id" => $this->getId(), + "title" => $this->getTitle(), + "type" => $this->getQuestiontype(), + "subtype" => $this->getSubtype(), + "obligatory" => $this->getObligatory() + ); + $a_xml_writer->xmlStartTag("question", $attrs); + + $a_xml_writer->xmlElement("description", null, $this->getDescription()); + $a_xml_writer->xmlElement("author", null, $this->getAuthor()); + $a_xml_writer->xmlStartTag("questiontext"); + $this->addMaterialTag($a_xml_writer, $this->getQuestiontext()); + $a_xml_writer->xmlEndTag("questiontext"); - $a_xml_writer->xmlStartTag("responses"); - switch ($this->getSubtype()) - { - case 3: - $attrs = array( - "id" => "0", - "format" => "double" - ); - if (strlen($this->getMinimum())) - { - $attrs["min"] = $this->getMinimum(); - } - if (strlen($this->getMaximum())) - { - $attrs["max"] = $this->getMaximum(); - } - break; - case 4: - $attrs = array( - "id" => "0", - "format" => "double" - ); - if (strlen($this->getMinimum())) - { - $attrs["min"] = $this->getMinimum(); - } - if (strlen($this->getMaximum())) - { - $attrs["max"] = $this->getMaximum(); - } - break; - case 5: - $attrs = array( - "id" => "0", - "format" => "integer" - ); - if (strlen($this->getMinimum())) - { - $attrs["min"] = $this->getMinimum(); - } - if (strlen($this->getMaximum())) - { - $attrs["max"] = $this->getMaximum(); - } - break; - } - $a_xml_writer->xmlStartTag("response_num", $attrs); - $a_xml_writer->xmlEndTag("response_num"); + $a_xml_writer->xmlStartTag("responses"); + switch ($this->getSubtype()) { + case 3: + $attrs = array( + "id" => "0", + "format" => "double" + ); + if (strlen($this->getMinimum())) { + $attrs["min"] = $this->getMinimum(); + } + if (strlen($this->getMaximum())) { + $attrs["max"] = $this->getMaximum(); + } + break; + case 4: + $attrs = array( + "id" => "0", + "format" => "double" + ); + if (strlen($this->getMinimum())) { + $attrs["min"] = $this->getMinimum(); + } + if (strlen($this->getMaximum())) { + $attrs["max"] = $this->getMaximum(); + } + break; + case 5: + $attrs = array( + "id" => "0", + "format" => "integer" + ); + if (strlen($this->getMinimum())) { + $attrs["min"] = $this->getMinimum(); + } + if (strlen($this->getMaximum())) { + $attrs["max"] = $this->getMaximum(); + } + break; + } + $a_xml_writer->xmlStartTag("response_num", $attrs); + $a_xml_writer->xmlEndTag("response_num"); - $a_xml_writer->xmlEndTag("responses"); + $a_xml_writer->xmlEndTag("responses"); - if (count($this->material)) - { - if (preg_match("/il_(\d*?)_(\w+)_(\d+)/", $this->material["internal_link"], $matches)) - { - $attrs = array( - "label" => $this->material["title"] - ); - $a_xml_writer->xmlStartTag("material", $attrs); - $intlink = "il_" . IL_INST_ID . "_" . $matches[2] . "_" . $matches[3]; - if (strcmp($matches[1], "") != 0) - { - $intlink = $this->material["internal_link"]; - } - $a_xml_writer->xmlElement("mattext", NULL, $intlink); - $a_xml_writer->xmlEndTag("material"); - } - } - - $a_xml_writer->xmlEndTag("question"); - } + if (count($this->material)) { + if (preg_match("/il_(\d*?)_(\w+)_(\d+)/", $this->material["internal_link"], $matches)) { + $attrs = array( + "label" => $this->material["title"] + ); + $a_xml_writer->xmlStartTag("material", $attrs); + $intlink = "il_" . IL_INST_ID . "_" . $matches[2] . "_" . $matches[3]; + if (strcmp($matches[1], "") != 0) { + $intlink = $this->material["internal_link"]; + } + $a_xml_writer->xmlElement("mattext", null, $intlink); + $a_xml_writer->xmlEndTag("material"); + } + } + + $a_xml_writer->xmlEndTag("question"); + } - /** - * Returns the question type ID of the question - * - * @return integer The question type of the question - * @access public - */ - function getQuestionTypeID() - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT questiontype_id FROM svy_qtype WHERE type_tag = %s", - array('text'), - array($this->getQuestionType()) - ); - $row = $ilDB->fetchAssoc($result); - return $row["questiontype_id"]; - } + /** + * Returns the question type ID of the question + * + * @return integer The question type of the question + * @access public + */ + public function getQuestionTypeID() + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT questiontype_id FROM svy_qtype WHERE type_tag = %s", + array('text'), + array($this->getQuestionType()) + ); + $row = $ilDB->fetchAssoc($result); + return $row["questiontype_id"]; + } - /** - * Returns the question type of the question - * - * @return integer The question type of the question - * @access public - */ - function getQuestionType() - { - return "SurveyMetricQuestion"; - } - - /** - * Returns the name of the additional question data table in the database - * - * @return string The additional table name - * @access public - */ - function getAdditionalTableName() - { - return "svy_qst_metric"; - } - - /** - * Creates the user data of the svy_answer table from the POST data - * - * @return array User data according to the svy_answer table - * @access public - */ - function &getWorkingDataFromUserInput($post_data) - { - $entered_value = $post_data[$this->getId() . "_metric_question"]; - $data = array(); - if (strlen($entered_value)) - { - array_push($data, array("value" => $entered_value)); - } - return $data; - } - - /** - * Checks the input of the active user for obligatory status - * and entered values - * - * @param array $post_data The contents of the $_POST array - * @param integer $survey_id The database ID of the active survey - * @return string Empty string if the input is ok, an error message otherwise - * @access public - */ - function checkUserInput($post_data, $survey_id) - { - $entered_value = $post_data[$this->getId() . "_metric_question"]; - // replace german notation with international notation - $entered_value = str_replace(",", ".", $entered_value); - - if ((!$this->getObligatory($survey_id)) && (strlen($entered_value) == 0)) return ""; - - if (strlen($entered_value) == 0) return $this->lng->txt("survey_question_obligatory"); - - if (strlen($this->getMinimum())) - { - if ($entered_value < $this->getMinimum()) - { - return $this->lng->txt("metric_question_out_of_bounds"); - } - } + /** + * Returns the question type of the question + * + * @return integer The question type of the question + * @access public + */ + public function getQuestionType() + { + return "SurveyMetricQuestion"; + } + + /** + * Returns the name of the additional question data table in the database + * + * @return string The additional table name + * @access public + */ + public function getAdditionalTableName() + { + return "svy_qst_metric"; + } + + /** + * Creates the user data of the svy_answer table from the POST data + * + * @return array User data according to the svy_answer table + * @access public + */ + public function &getWorkingDataFromUserInput($post_data) + { + $entered_value = $post_data[$this->getId() . "_metric_question"]; + $data = array(); + if (strlen($entered_value)) { + array_push($data, array("value" => $entered_value)); + } + return $data; + } + + /** + * Checks the input of the active user for obligatory status + * and entered values + * + * @param array $post_data The contents of the $_POST array + * @param integer $survey_id The database ID of the active survey + * @return string Empty string if the input is ok, an error message otherwise + * @access public + */ + public function checkUserInput($post_data, $survey_id) + { + $entered_value = $post_data[$this->getId() . "_metric_question"]; + // replace german notation with international notation + $entered_value = str_replace(",", ".", $entered_value); + + if ((!$this->getObligatory($survey_id)) && (strlen($entered_value) == 0)) { + return ""; + } + + if (strlen($entered_value) == 0) { + return $this->lng->txt("survey_question_obligatory"); + } + + if (strlen($this->getMinimum())) { + if ($entered_value < $this->getMinimum()) { + return $this->lng->txt("metric_question_out_of_bounds"); + } + } - if (strlen($this->getMaximum())) - { - if (($this->getMaximum() == 1) && ($this->getMaximum() < $this->getMinimum())) - { - // old &infty; values as maximum - } - else - { - if ($entered_value > $this->getMaximum()) - { - return $this->lng->txt("metric_question_out_of_bounds"); - } - } - } + if (strlen($this->getMaximum())) { + if (($this->getMaximum() == 1) && ($this->getMaximum() < $this->getMinimum())) { + // old &infty; values as maximum + } else { + if ($entered_value > $this->getMaximum()) { + return $this->lng->txt("metric_question_out_of_bounds"); + } + } + } - if (!is_numeric($entered_value)) - { - return $this->lng->txt("metric_question_not_a_value"); - } + if (!is_numeric($entered_value)) { + return $this->lng->txt("metric_question_not_a_value"); + } - if (($this->getSubType() == self::SUBTYPE_RATIO_ABSOLUTE) && (intval($entered_value) != doubleval($entered_value))) - { - return $this->lng->txt("metric_question_floating_point"); - } - return ""; - } - - function saveUserInput($post_data, $active_id, $a_return = false) - { - $ilDB = $this->db; - - $entered_value = $post_data[$this->getId() . "_metric_question"]; - - // replace german notation with international notation - $entered_value = str_replace(",", ".", $entered_value); - - if($a_return) - { - return array(array("value"=>$entered_value, "textanswer"=>null)); - } - if (strlen($entered_value) == 0) return; - - $next_id = $ilDB->nextId('svy_answer'); - #20216 - $fields = array(); - $fields['answer_id'] = array("integer", $next_id); - $fields['question_fi'] = array("integer", $this->getId()); - $fields['active_fi'] = array("integer", $active_id); - $fields['value'] = array("float", (strlen($entered_value)) ? $entered_value : NULL); - $fields['textanswer'] = array("clob", NULL); - $fields['tstamp'] = array("integer", time()); + if (($this->getSubType() == self::SUBTYPE_RATIO_ABSOLUTE) && (intval($entered_value) != doubleval($entered_value))) { + return $this->lng->txt("metric_question_floating_point"); + } + return ""; + } + + public function saveUserInput($post_data, $active_id, $a_return = false) + { + $ilDB = $this->db; + + $entered_value = $post_data[$this->getId() . "_metric_question"]; + + // replace german notation with international notation + $entered_value = str_replace(",", ".", $entered_value); + + if ($a_return) { + return array(array("value"=>$entered_value, "textanswer"=>null)); + } + if (strlen($entered_value) == 0) { + return; + } + + $next_id = $ilDB->nextId('svy_answer'); + #20216 + $fields = array(); + $fields['answer_id'] = array("integer", $next_id); + $fields['question_fi'] = array("integer", $this->getId()); + $fields['active_fi'] = array("integer", $active_id); + $fields['value'] = array("float", (strlen($entered_value)) ? $entered_value : null); + $fields['textanswer'] = array("clob", null); + $fields['tstamp'] = array("integer", time()); - $affectedRows = $ilDB->insert("svy_answer", $fields); - } + $affectedRows = $ilDB->insert("svy_answer", $fields); + } - /** - * Import response data from the question import file - * - * @return array $a_data Array containing the response data - * @access public - */ - function importResponses($a_data) - { - foreach ($a_data as $id => $data) - { - $this->setMinimum($data["min"]); - $this->setMaximum($data["max"]); - } - } + /** + * Import response data from the question import file + * + * @return array $a_data Array containing the response data + * @access public + */ + public function importResponses($a_data) + { + foreach ($a_data as $id => $data) { + $this->setMinimum($data["min"]); + $this->setMaximum($data["max"]); + } + } - /** - * Returns if the question is usable for preconditions - * - * @return boolean TRUE if the question is usable for a precondition, FALSE otherwise - * @access public - */ - function usableForPrecondition() - { - return TRUE; - } + /** + * Returns if the question is usable for preconditions + * + * @return boolean TRUE if the question is usable for a precondition, FALSE otherwise + * @access public + */ + public function usableForPrecondition() + { + return true; + } - /** - * Returns the available relations for the question - * - * @return array An array containing the available relations - * @access public - */ - function getAvailableRelations() - { - return array("<", "<=", "=", "<>", ">=", ">"); - } + /** + * Returns the available relations for the question + * + * @return array An array containing the available relations + * @access public + */ + public function getAvailableRelations() + { + return array("<", "<=", "=", "<>", ">=", ">"); + } - /** - * Creates a value selection for preconditions - * - * @param object $template The template for the value selection (usually tpl.svy_svy_add_constraint.html) - * @access public - */ - function outPreconditionSelectValue(&$template) - { - $template->setCurrentBlock("textfield"); - $template->setVariable("TEXTFIELD_VALUE", ""); - $template->parseCurrentBlock(); - } - - /** - * Creates a form property for the precondition value - * - * @return The ILIAS form element - * @access public - */ - public function getPreconditionSelectValue($default = "", $title, $variable) - { - include_once "./Services/Form/classes/class.ilNumberInputGUI.php"; - $step3 = new ilNumberInputGUI($title, $variable); - $step3->setValue($default); - return $step3; - } + /** + * Creates a value selection for preconditions + * + * @param object $template The template for the value selection (usually tpl.svy_svy_add_constraint.html) + * @access public + */ + public function outPreconditionSelectValue(&$template) + { + $template->setCurrentBlock("textfield"); + $template->setVariable("TEXTFIELD_VALUE", ""); + $template->parseCurrentBlock(); + } + + /** + * Creates a form property for the precondition value + * + * @return The ILIAS form element + * @access public + */ + public function getPreconditionSelectValue($default = "", $title, $variable) + { + include_once "./Services/Form/classes/class.ilNumberInputGUI.php"; + $step3 = new ilNumberInputGUI($title, $variable); + $step3->setValue($default); + return $step3; + } - /** - * Creates a text for the input range of the metric question - * - * @return string Range text - * @access private - */ - function getMinMaxText() - { - $min = $this->getMinimum(); - $max = $this->getMaximum(); - if (strlen($min) && strlen($max)) - { - return "(" . $min . " " . strtolower($this->lng->txt("to")) . " " . $max . ")"; - } - else if (strlen($min)) - { - return "(>= " . $min . ")"; - } - else if (strlen($max)) - { - return "(<= " . $max . ")"; - } - else - { - return ""; - } - } + /** + * Creates a text for the input range of the metric question + * + * @return string Range text + * @access private + */ + public function getMinMaxText() + { + $min = $this->getMinimum(); + $max = $this->getMaximum(); + if (strlen($min) && strlen($max)) { + return "(" . $min . " " . strtolower($this->lng->txt("to")) . " " . $max . ")"; + } elseif (strlen($min)) { + return "(>= " . $min . ")"; + } elseif (strlen($max)) { + return "(<= " . $max . ")"; + } else { + return ""; + } + } } -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyMetricQuestionEvaluation.php b/Modules/SurveyQuestionPool/classes/class.SurveyMetricQuestionEvaluation.php index 3178065e362b58bc03110585dcb127b75486b507..43e77a6b3eb483fe744ee38e68b77b2d9f6fc929 100644 --- a/Modules/SurveyQuestionPool/classes/class.SurveyMetricQuestionEvaluation.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyMetricQuestionEvaluation.php @@ -4,209 +4,184 @@ include_once "Modules/SurveyQuestionPool/classes/class.SurveyQuestionEvaluation.php"; /** - * Survey metric evaluation + * Survey metric evaluation * * @author Jörg Lützenkirchen$error_message
"); - } - $template->parseCurrentBlock(); - return $template->get(); - } + if (strcmp($error_message, "") != 0) { + $template->setVariable("ERROR_MESSAGE", "$error_message
"); + } + $template->parseCurrentBlock(); + return $template->get(); + } } - -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyMultipleChoiceQuestion.php b/Modules/SurveyQuestionPool/classes/class.SurveyMultipleChoiceQuestion.php index 8ddfc864713c0b78cd216c942f6eb14ec1cbfee2..58716efc5a6e203eeb5042e4c98948eb94009b23 100755 --- a/Modules/SurveyQuestionPool/classes/class.SurveyMultipleChoiceQuestion.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyMultipleChoiceQuestion.php @@ -34,594 +34,560 @@ include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; * @extends SurveyQuestion * @ingroup ModulesSurveyQuestionPool */ -class SurveyMultipleChoiceQuestion extends SurveyQuestion +class SurveyMultipleChoiceQuestion extends SurveyQuestion { - /** - * @var ilDB - */ - protected $db; - -/** -* Categories contained in this question -* -* @var array -*/ - var $categories; - -/** -* The constructor takes possible arguments an creates an instance of the SurveyMultipleChoiceQuestion object. -* -* @param string $title A title string to describe the question -* @param string $description A description string to describe the question -* @param string $author A string containing the name of the questions author -* @param integer $owner A numerical ID to identify the owner/creator -* @access public -*/ - function __construct($title = "", $description = "", $author = "", $questiontext = "", $owner = -1, $orientation = 0) - { - global $DIC; - - $this->db = $DIC->database(); - $this->lng = $DIC->language(); - parent::__construct($title, $description, $author, $questiontext, $owner); - - $this->orientation = $orientation; - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; - $this->categories = new SurveyCategories(); - } - - /** - * Returns the question data fields from the database - * - * @param integer $id The question ID from the database - * @return array Array containing the question fields and data from the database - * @access public - */ - function getQuestionDataArray($id) - { - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT svy_question.*, " . $this->getAdditionalTableName() . ".* FROM svy_question, " . $this->getAdditionalTableName() . " WHERE svy_question.question_id = %s AND svy_question.question_id = " . $this->getAdditionalTableName() . ".question_fi", - array('integer'), - array($id) - ); - if ($result->numRows() == 1) - { - return $ilDB->fetchAssoc($result); - } - else - { - return array(); - } - } - -/** -* Loads a SurveyMultipleChoiceQuestion object from the database -* -* @param integer $id The database id of the multiple choice survey question -* @access public -*/ - function loadFromDb($id) - { - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT svy_question.*, " . $this->getAdditionalTableName() . ".* FROM svy_question LEFT JOIN " . $this->getAdditionalTableName() . " ON " . $this->getAdditionalTableName() . ".question_fi = svy_question.question_id WHERE svy_question.question_id = %s", - array('integer'), - array($id) - ); - if ($result->numRows() == 1) - { - $data = $ilDB->fetchAssoc($result); - $this->setId($data["question_id"]); - $this->setTitle($data["title"]); - $this->label = $data['label']; - $this->setDescription($data["description"]); - $this->setObjId($data["obj_fi"]); - $this->setAuthor($data["author"]); - $this->setOwner($data["owner_fi"]); - include_once("./Services/RTE/classes/class.ilRTE.php"); - $this->setQuestiontext(ilRTE::_replaceMediaObjectImageSrc($data["questiontext"], 1)); - $this->setObligatory($data["obligatory"]); - $this->setComplete($data["complete"]); - $this->setOriginalId($data["original_id"]); - $this->setOrientation($data["orientation"]); - $this->use_min_answers = ($data['use_min_answers']) ? true : false; - $this->nr_min_answers = $data['nr_min_answers']; - $this->nr_max_answers = $data['nr_max_answers']; - - $this->categories->flushCategories(); - $result = $ilDB->queryF("SELECT svy_variable.*, svy_category.title, svy_category.neutral FROM svy_variable, svy_category WHERE svy_variable.question_fi = %s AND svy_variable.category_fi = svy_category.category_id ORDER BY sequence ASC", - array('integer'), - array($id) - ); - if ($result->numRows() > 0) - { - while ($data = $ilDB->fetchAssoc($result)) - { - $this->categories->addCategory($data["title"], $data["other"], $data["neutral"], null, ($data['scale']) ? $data['scale'] : ($data['sequence'] + 1)); - } - } - } - parent::loadFromDb($id); - } - -/** -* Returns true if the question is complete for use -* -* @result boolean True if the question is complete for use, otherwise false -* @access public -*/ - function isComplete() - { - if ( - strlen($this->getTitle()) && - strlen($this->getAuthor()) && - strlen($this->getQuestiontext()) && - $this->categories->getCategoryCount() - ) - { - return 1; - } - else - { - return 0; - } - } - -/** -* Saves a SurveyMultipleChoiceQuestion object to a database -* -* @access public -*/ - function saveToDb($original_id = "") - { - $ilDB = $this->db; - - $affectedRows = parent::saveToDb($original_id); - if ($affectedRows == 1) - { - $affectedRows = $ilDB->manipulateF("DELETE FROM " . $this->getAdditionalTableName() . " WHERE question_fi = %s", - array('integer'), - array($this->getId()) - ); - $affectedRows = $ilDB->manipulateF("INSERT INTO " . $this->getAdditionalTableName() . " (question_fi, orientation, use_min_answers, nr_min_answers, nr_max_answers) VALUES (%s, %s, %s, %s, %s)", - array('integer', 'text', 'integer', 'integer', 'integer'), - array( - $this->getId(), - $this->getOrientation(), - ($this->use_min_answers) ? 1 : 0, - ($this->nr_min_answers > 0) ? $this->nr_min_answers : null, - ($this->nr_max_answers > 0) ? $this->nr_max_answers : null - ) - ); - - // saving material uris in the database - $this->saveMaterial(); - $this->saveCategoriesToDb(); - } - } - - function saveCategoriesToDb() - { - $ilDB = $this->db; - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_variable WHERE question_fi = %s", - array('integer'), - array($this->getId()) - ); - - for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) - { - $cat = $this->categories->getCategory($i); - $category_id = $this->saveCategoryToDb($cat->title, $cat->neutral); - $next_id = $ilDB->nextId('svy_variable'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_variable (variable_id, category_fi, question_fi, value1, other, sequence, scale, tstamp) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", - array('integer','integer','integer','float','integer','integer', 'integer','integer'), - array($next_id, $category_id, $this->getId(), ($i + 1), $cat->other, $i, ($cat->scale > 0) ? $cat->scale : null, time()) - ); - } - $this->saveCompletionStatus(); - } - - /** - * Returns an xml representation of the question - * - * @return string The xml representation of the question - * @access public - */ - function toXML($a_include_header = TRUE, $obligatory_state = "") - { - include_once("./Services/Xml/classes/class.ilXmlWriter.php"); - $a_xml_writer = new ilXmlWriter; - $a_xml_writer->xmlHeader(); - $this->insertXML($a_xml_writer, $a_include_header, $obligatory_state); - $xml = $a_xml_writer->xmlDumpMem(FALSE); - if (!$a_include_header) - { - $pos = strpos($xml, "?>"); - $xml = substr($xml, $pos + 2); - } - return $xml; - } - - /** - * Adds the question XML to a given XMLWriter object - * - * @param object $a_xml_writer The XMLWriter object - * @param boolean $a_include_header Determines wheather or not the XML should be used - * @access public - */ - function insertXML(&$a_xml_writer, $a_include_header = TRUE) - { - $attrs = array( - "id" => $this->getId(), - "title" => $this->getTitle(), - "type" => $this->getQuestiontype(), - "obligatory" => $this->getObligatory() - ); - $a_xml_writer->xmlStartTag("question", $attrs); - - $a_xml_writer->xmlElement("description", NULL, $this->getDescription()); - $a_xml_writer->xmlElement("author", NULL, $this->getAuthor()); - if (strlen($this->label)) - { - $attrs = array( - "label" => $this->label, - ); - } - else - { - $attrs = array(); - } - $a_xml_writer->xmlStartTag("questiontext", $attrs); - $this->addMaterialTag($a_xml_writer, $this->getQuestiontext()); - $a_xml_writer->xmlEndTag("questiontext"); - - $a_xml_writer->xmlStartTag("responses"); - - for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) - { - $attrs = array( - "id" => $i - ); - if (strlen($this->categories->getCategory($i)->other)) $attrs['other'] = $this->categories->getCategory($i)->other; - if (strlen($this->categories->getCategory($i)->neutral)) $attrs['neutral'] = $this->categories->getCategory($i)->neutral; - if (strlen($this->categories->getCategory($i)->label)) $attrs['label'] = $this->categories->getCategory($i)->label; - if (strlen($this->categories->getCategory($i)->scale)) $attrs['scale'] = $this->categories->getCategory($i)->scale; - $a_xml_writer->xmlStartTag("response_multiple", $attrs); - $this->addMaterialTag($a_xml_writer, $this->categories->getCategory($i)->title); - $a_xml_writer->xmlEndTag("response_multiple"); - } - - $a_xml_writer->xmlEndTag("responses"); - - if (count($this->material)) - { - if (preg_match("/il_(\d*?)_(\w+)_(\d+)/", $this->material["internal_link"], $matches)) - { - $attrs = array( - "label" => $this->material["title"] - ); - $a_xml_writer->xmlStartTag("material", $attrs); - $intlink = "il_" . IL_INST_ID . "_" . $matches[2] . "_" . $matches[3]; - if (strcmp($matches[1], "") != 0) - { - $intlink = $this->material["internal_link"]; - } - $a_xml_writer->xmlElement("mattext", NULL, $intlink); - $a_xml_writer->xmlEndTag("material"); - } - } - - $a_xml_writer->xmlStartTag("metadata"); - $a_xml_writer->xmlStartTag("metadatafield"); - $a_xml_writer->xmlElement("fieldlabel", NULL, "orientation"); - $a_xml_writer->xmlElement("fieldentry", NULL, $this->getOrientation()); - $a_xml_writer->xmlEndTag("metadatafield"); - $a_xml_writer->xmlStartTag("metadatafield"); - $a_xml_writer->xmlElement("fieldlabel", NULL, "use_min_answers"); - $a_xml_writer->xmlElement("fieldentry", NULL, $this->use_min_answers); - $a_xml_writer->xmlEndTag("metadatafield"); - $a_xml_writer->xmlStartTag("metadatafield"); - $a_xml_writer->xmlElement("fieldlabel", NULL, "nr_min_answers"); - $a_xml_writer->xmlElement("fieldentry", NULL, $this->nr_min_answers); - $a_xml_writer->xmlEndTag("metadatafield"); - $a_xml_writer->xmlStartTag("metadatafield"); - $a_xml_writer->xmlElement("fieldlabel", NULL, "nr_max_answers"); - $a_xml_writer->xmlElement("fieldentry", NULL, $this->nr_max_answers); - $a_xml_writer->xmlEndTag("metadatafield"); - $a_xml_writer->xmlEndTag("metadata"); - - $a_xml_writer->xmlEndTag("question"); - } - - /** - * Returns the question type of the question - * - * @return integer The question type of the question - * @access public - */ - function getQuestionType() - { - return "SurveyMultipleChoiceQuestion"; - } - - /** - * Returns the name of the additional question data table in the database - * - * @return string The additional table name - * @access public - */ - function getAdditionalTableName() - { - return "svy_qst_mc"; - } - - /** - * Creates the user data of the svy_answer table from the POST data - * - * @return array User data according to the svy_answer table - * @access public - */ - function &getWorkingDataFromUserInput($post_data) - { - $entered_value = $post_data[$this->getId() . "_value"]; - $data = array(); - if (is_array($entered_value)) - { - foreach ($entered_value as $idx => $value) - { - array_push($data, array("value" => $value, "textanswer" => $post_data[$this->getId() . '_' . $value . '_other'])); - } - } - for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) - { - $cat = $this->categories->getCategory($i); - if ($cat->other) - { - // #18212 - if (!is_array($entered_value) || !in_array($i, $entered_value)) - { - if (strlen($post_data[$this->getId() . "_" . $i . "_other"])) - { - array_push($data, array("value" => $i, "textanswer" => $post_data[$this->getId() . '_' . $i . '_other'], "uncheck" => true)); - } - } - } - } - return $data; - } - - /** - * Checks the input of the active user for obligatory status - * and entered values - * - * @param array $post_data The contents of the $_POST array - * @param integer $survey_id The database ID of the active survey - * @return string Empty string if the input is ok, an error message otherwise - * @access public - */ - function checkUserInput($post_data, $survey_id) - { - $entered_value = $post_data[$this->getId() . "_value"]; - if (!$this->getObligatory($survey_id) && (!is_array($entered_value) || count($entered_value) == 0)) return ""; - - if ($this->use_min_answers && $this->nr_min_answers > 0 && $this->nr_max_answers > 0 && $this->nr_min_answers == $this->nr_max_answers && count($entered_value) != $this->nr_max_answers) - { - return sprintf($this->lng->txt("err_no_exact_answers"), $this->nr_min_answers); - } - if ($this->use_min_answers && $this->nr_min_answers > 0 && count($entered_value) < $this->nr_min_answers) - { - return sprintf($this->lng->txt("err_no_min_answers"), $this->nr_min_answers); - } - if ($this->use_min_answers && $this->nr_max_answers > 0 && count($entered_value) > $this->nr_max_answers) - { - return sprintf($this->lng->txt("err_no_max_answers"), $this->nr_max_answers); - } - if (!is_array($entered_value)) - { - return $this->lng->txt("question_mr_not_checked"); - } - for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) - { - $cat = $this->categories->getCategory($i); - if ($cat->other) - { - if (in_array($i, $entered_value)) - { - if (array_key_exists($this->getId() . "_" . $i . "_other", $post_data) && !strlen($post_data[$this->getId() . "_" . $i . "_other"])) - { - return $this->lng->txt("question_mr_no_other_answer"); - } - } - else - { - if (strlen($post_data[$this->getId() . "_" . $i . "_other"])) - { - return $this->lng->txt("question_mr_no_other_answer_checked"); - } - } - } - } - return ""; - } - - function saveUserInput($post_data, $active_id, $a_return = false) - { - $ilDB = $this->db; - - if($a_return) - { - $return_data = array(); - } - if (is_array($post_data[$this->getId() . "_value"])) - { - foreach ($post_data[$this->getId() . "_value"] as $entered_value) - { - if (strlen($entered_value) > 0) - { - if(!$a_return) - { - $next_id = $ilDB->nextId('svy_answer'); - - #20216 - $fields = array(); - $fields['answer_id'] = array("integer", $next_id); - $fields['question_fi'] = array("integer", $this->getId()); - $fields['active_fi'] = array("integer", $active_id); - $fields['value'] = array("float", (strlen($entered_value)) ? $entered_value : NULL); - $fields['textanswer'] = array("clob", ($post_data[$this->getId() . "_" . $entered_value . "_other"]) ? $post_data[$this->getId() . "_" . $entered_value . "_other"] : null); - $fields['tstamp'] = array("integer", time()); - - $affectedRows = $ilDB->insert("svy_answer", $fields); - } - else - { - $return_data[] = array("value"=>$entered_value, - "textanswer"=>$post_data[$this->getId() . "_" . $entered_value . "_other"]); - } - } - } - } - if($a_return) - { - return $return_data; - } - } - - /** - * Import additional meta data from the question import file. Usually - * the meta data section is used to store question elements which are not - * part of the standard XML schema. - * - * @return array $a_meta Array containing the additional meta data - * @access public - */ - function importAdditionalMetadata($a_meta) - { - foreach ($a_meta as $key => $value) - { - switch ($value["label"]) - { - case "orientation": - $this->setOrientation($value["entry"]); - break; - case "use_min_answers": - $this->use_min_answers = $value["entry"]; - break; - case "nr_min_answers": - $this->nr_min_answers = $value["entry"]; - break; - case "nr_max_answers": - $this->nr_max_answers = $value["entry"]; - break; - } - } - } - - /** - * Import response data from the question import file - * - * @return array $a_data Array containing the response data - * @access public - */ - function importResponses($a_data) - { - foreach ($a_data as $id => $data) - { - $categorytext = ""; - foreach ($data["material"] as $material) - { - $categorytext .= $material["text"]; - } - $this->categories->addCategory( - $categorytext, - strlen($data['other']) ? $data['other'] : 0, - strlen($data['neutral']) ? $data['neutral'] : 0, - strlen($data['label']) ? $data['label'] : null, - strlen($data['scale']) ? $data['scale'] : null - ); - } - } - - /** - * Returns if the question is usable for preconditions - * - * @return boolean TRUE if the question is usable for a precondition, FALSE otherwise - * @access public - */ - function usableForPrecondition() - { - return TRUE; - } - - /** - * Returns the available relations for the question - * - * @return array An array containing the available relations - * @access public - */ - function getAvailableRelations() - { - return array("=", "<>"); - } - - /** - * Returns the options for preconditions - * - * @return array - */ - public function getPreconditionOptions() - { - $lng = $this->lng; - - $options = array(); - for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) - { - $category = $this->categories->getCategory($i); - $options[$category->scale-1] = $category->scale . " - " . $category->title; - } - return $options; - } - - /** - * Creates a form property for the precondition value - * - * @return The ILIAS form element - * @access public - */ - public function getPreconditionSelectValue($default = "", $title, $variable) - { - include_once "./Services/Form/classes/class.ilSelectInputGUI.php"; - $step3 = new ilSelectInputGUI($title, $variable); - $options = $this->getPreconditionOptions(); - $step3->setOptions($options); - $step3->setValue($default); - return $step3; - } - - /** - * Returns the output for a precondition value - * - * @param string $value The precondition value - * @return string The output of the precondition value - * @access public - */ - function getPreconditionValueOutput($value) - { - // #18136 - $category = $this->categories->getCategoryForScale($value+1); - - // #17895 - see getPreconditionOptions() - return $category->scale . - " - " . - ((strlen($category->title)) ? $category->title : $this->lng->txt('other_answer')); - } - - public function getCategories() - { - return $this->categories; - } - + /** + * @var ilDB + */ + protected $db; + + /** + * Categories contained in this question + * + * @var array + */ + public $categories; + + /** + * The constructor takes possible arguments an creates an instance of the SurveyMultipleChoiceQuestion object. + * + * @param string $title A title string to describe the question + * @param string $description A description string to describe the question + * @param string $author A string containing the name of the questions author + * @param integer $owner A numerical ID to identify the owner/creator + * @access public + */ + public function __construct($title = "", $description = "", $author = "", $questiontext = "", $owner = -1, $orientation = 0) + { + global $DIC; + + $this->db = $DIC->database(); + $this->lng = $DIC->language(); + parent::__construct($title, $description, $author, $questiontext, $owner); + + $this->orientation = $orientation; + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyCategories.php"; + $this->categories = new SurveyCategories(); + } + + /** + * Returns the question data fields from the database + * + * @param integer $id The question ID from the database + * @return array Array containing the question fields and data from the database + * @access public + */ + public function getQuestionDataArray($id) + { + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT svy_question.*, " . $this->getAdditionalTableName() . ".* FROM svy_question, " . $this->getAdditionalTableName() . " WHERE svy_question.question_id = %s AND svy_question.question_id = " . $this->getAdditionalTableName() . ".question_fi", + array('integer'), + array($id) + ); + if ($result->numRows() == 1) { + return $ilDB->fetchAssoc($result); + } else { + return array(); + } + } + + /** + * Loads a SurveyMultipleChoiceQuestion object from the database + * + * @param integer $id The database id of the multiple choice survey question + * @access public + */ + public function loadFromDb($id) + { + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT svy_question.*, " . $this->getAdditionalTableName() . ".* FROM svy_question LEFT JOIN " . $this->getAdditionalTableName() . " ON " . $this->getAdditionalTableName() . ".question_fi = svy_question.question_id WHERE svy_question.question_id = %s", + array('integer'), + array($id) + ); + if ($result->numRows() == 1) { + $data = $ilDB->fetchAssoc($result); + $this->setId($data["question_id"]); + $this->setTitle($data["title"]); + $this->label = $data['label']; + $this->setDescription($data["description"]); + $this->setObjId($data["obj_fi"]); + $this->setAuthor($data["author"]); + $this->setOwner($data["owner_fi"]); + include_once("./Services/RTE/classes/class.ilRTE.php"); + $this->setQuestiontext(ilRTE::_replaceMediaObjectImageSrc($data["questiontext"], 1)); + $this->setObligatory($data["obligatory"]); + $this->setComplete($data["complete"]); + $this->setOriginalId($data["original_id"]); + $this->setOrientation($data["orientation"]); + $this->use_min_answers = ($data['use_min_answers']) ? true : false; + $this->nr_min_answers = $data['nr_min_answers']; + $this->nr_max_answers = $data['nr_max_answers']; + + $this->categories->flushCategories(); + $result = $ilDB->queryF( + "SELECT svy_variable.*, svy_category.title, svy_category.neutral FROM svy_variable, svy_category WHERE svy_variable.question_fi = %s AND svy_variable.category_fi = svy_category.category_id ORDER BY sequence ASC", + array('integer'), + array($id) + ); + if ($result->numRows() > 0) { + while ($data = $ilDB->fetchAssoc($result)) { + $this->categories->addCategory($data["title"], $data["other"], $data["neutral"], null, ($data['scale']) ? $data['scale'] : ($data['sequence'] + 1)); + } + } + } + parent::loadFromDb($id); + } + + /** + * Returns true if the question is complete for use + * + * @result boolean True if the question is complete for use, otherwise false + * @access public + */ + public function isComplete() + { + if ( + strlen($this->getTitle()) && + strlen($this->getAuthor()) && + strlen($this->getQuestiontext()) && + $this->categories->getCategoryCount() + ) { + return 1; + } else { + return 0; + } + } + + /** + * Saves a SurveyMultipleChoiceQuestion object to a database + * + * @access public + */ + public function saveToDb($original_id = "") + { + $ilDB = $this->db; + + $affectedRows = parent::saveToDb($original_id); + if ($affectedRows == 1) { + $affectedRows = $ilDB->manipulateF( + "DELETE FROM " . $this->getAdditionalTableName() . " WHERE question_fi = %s", + array('integer'), + array($this->getId()) + ); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO " . $this->getAdditionalTableName() . " (question_fi, orientation, use_min_answers, nr_min_answers, nr_max_answers) VALUES (%s, %s, %s, %s, %s)", + array('integer', 'text', 'integer', 'integer', 'integer'), + array( + $this->getId(), + $this->getOrientation(), + ($this->use_min_answers) ? 1 : 0, + ($this->nr_min_answers > 0) ? $this->nr_min_answers : null, + ($this->nr_max_answers > 0) ? $this->nr_max_answers : null + ) + ); + + // saving material uris in the database + $this->saveMaterial(); + $this->saveCategoriesToDb(); + } + } + + public function saveCategoriesToDb() + { + $ilDB = $this->db; + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_variable WHERE question_fi = %s", + array('integer'), + array($this->getId()) + ); + + for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) { + $cat = $this->categories->getCategory($i); + $category_id = $this->saveCategoryToDb($cat->title, $cat->neutral); + $next_id = $ilDB->nextId('svy_variable'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_variable (variable_id, category_fi, question_fi, value1, other, sequence, scale, tstamp) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", + array('integer','integer','integer','float','integer','integer', 'integer','integer'), + array($next_id, $category_id, $this->getId(), ($i + 1), $cat->other, $i, ($cat->scale > 0) ? $cat->scale : null, time()) + ); + } + $this->saveCompletionStatus(); + } + + /** + * Returns an xml representation of the question + * + * @return string The xml representation of the question + * @access public + */ + public function toXML($a_include_header = true, $obligatory_state = "") + { + include_once("./Services/Xml/classes/class.ilXmlWriter.php"); + $a_xml_writer = new ilXmlWriter; + $a_xml_writer->xmlHeader(); + $this->insertXML($a_xml_writer, $a_include_header, $obligatory_state); + $xml = $a_xml_writer->xmlDumpMem(false); + if (!$a_include_header) { + $pos = strpos($xml, "?>"); + $xml = substr($xml, $pos + 2); + } + return $xml; + } + + /** + * Adds the question XML to a given XMLWriter object + * + * @param object $a_xml_writer The XMLWriter object + * @param boolean $a_include_header Determines wheather or not the XML should be used + * @access public + */ + public function insertXML(&$a_xml_writer, $a_include_header = true) + { + $attrs = array( + "id" => $this->getId(), + "title" => $this->getTitle(), + "type" => $this->getQuestiontype(), + "obligatory" => $this->getObligatory() + ); + $a_xml_writer->xmlStartTag("question", $attrs); + + $a_xml_writer->xmlElement("description", null, $this->getDescription()); + $a_xml_writer->xmlElement("author", null, $this->getAuthor()); + if (strlen($this->label)) { + $attrs = array( + "label" => $this->label, + ); + } else { + $attrs = array(); + } + $a_xml_writer->xmlStartTag("questiontext", $attrs); + $this->addMaterialTag($a_xml_writer, $this->getQuestiontext()); + $a_xml_writer->xmlEndTag("questiontext"); + + $a_xml_writer->xmlStartTag("responses"); + + for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) { + $attrs = array( + "id" => $i + ); + if (strlen($this->categories->getCategory($i)->other)) { + $attrs['other'] = $this->categories->getCategory($i)->other; + } + if (strlen($this->categories->getCategory($i)->neutral)) { + $attrs['neutral'] = $this->categories->getCategory($i)->neutral; + } + if (strlen($this->categories->getCategory($i)->label)) { + $attrs['label'] = $this->categories->getCategory($i)->label; + } + if (strlen($this->categories->getCategory($i)->scale)) { + $attrs['scale'] = $this->categories->getCategory($i)->scale; + } + $a_xml_writer->xmlStartTag("response_multiple", $attrs); + $this->addMaterialTag($a_xml_writer, $this->categories->getCategory($i)->title); + $a_xml_writer->xmlEndTag("response_multiple"); + } + + $a_xml_writer->xmlEndTag("responses"); + + if (count($this->material)) { + if (preg_match("/il_(\d*?)_(\w+)_(\d+)/", $this->material["internal_link"], $matches)) { + $attrs = array( + "label" => $this->material["title"] + ); + $a_xml_writer->xmlStartTag("material", $attrs); + $intlink = "il_" . IL_INST_ID . "_" . $matches[2] . "_" . $matches[3]; + if (strcmp($matches[1], "") != 0) { + $intlink = $this->material["internal_link"]; + } + $a_xml_writer->xmlElement("mattext", null, $intlink); + $a_xml_writer->xmlEndTag("material"); + } + } + + $a_xml_writer->xmlStartTag("metadata"); + $a_xml_writer->xmlStartTag("metadatafield"); + $a_xml_writer->xmlElement("fieldlabel", null, "orientation"); + $a_xml_writer->xmlElement("fieldentry", null, $this->getOrientation()); + $a_xml_writer->xmlEndTag("metadatafield"); + $a_xml_writer->xmlStartTag("metadatafield"); + $a_xml_writer->xmlElement("fieldlabel", null, "use_min_answers"); + $a_xml_writer->xmlElement("fieldentry", null, $this->use_min_answers); + $a_xml_writer->xmlEndTag("metadatafield"); + $a_xml_writer->xmlStartTag("metadatafield"); + $a_xml_writer->xmlElement("fieldlabel", null, "nr_min_answers"); + $a_xml_writer->xmlElement("fieldentry", null, $this->nr_min_answers); + $a_xml_writer->xmlEndTag("metadatafield"); + $a_xml_writer->xmlStartTag("metadatafield"); + $a_xml_writer->xmlElement("fieldlabel", null, "nr_max_answers"); + $a_xml_writer->xmlElement("fieldentry", null, $this->nr_max_answers); + $a_xml_writer->xmlEndTag("metadatafield"); + $a_xml_writer->xmlEndTag("metadata"); + + $a_xml_writer->xmlEndTag("question"); + } + + /** + * Returns the question type of the question + * + * @return integer The question type of the question + * @access public + */ + public function getQuestionType() + { + return "SurveyMultipleChoiceQuestion"; + } + + /** + * Returns the name of the additional question data table in the database + * + * @return string The additional table name + * @access public + */ + public function getAdditionalTableName() + { + return "svy_qst_mc"; + } + + /** + * Creates the user data of the svy_answer table from the POST data + * + * @return array User data according to the svy_answer table + * @access public + */ + public function &getWorkingDataFromUserInput($post_data) + { + $entered_value = $post_data[$this->getId() . "_value"]; + $data = array(); + if (is_array($entered_value)) { + foreach ($entered_value as $idx => $value) { + array_push($data, array("value" => $value, "textanswer" => $post_data[$this->getId() . '_' . $value . '_other'])); + } + } + for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) { + $cat = $this->categories->getCategory($i); + if ($cat->other) { + // #18212 + if (!is_array($entered_value) || !in_array($i, $entered_value)) { + if (strlen($post_data[$this->getId() . "_" . $i . "_other"])) { + array_push($data, array("value" => $i, "textanswer" => $post_data[$this->getId() . '_' . $i . '_other'], "uncheck" => true)); + } + } + } + } + return $data; + } + + /** + * Checks the input of the active user for obligatory status + * and entered values + * + * @param array $post_data The contents of the $_POST array + * @param integer $survey_id The database ID of the active survey + * @return string Empty string if the input is ok, an error message otherwise + * @access public + */ + public function checkUserInput($post_data, $survey_id) + { + $entered_value = $post_data[$this->getId() . "_value"]; + if (!$this->getObligatory($survey_id) && (!is_array($entered_value) || count($entered_value) == 0)) { + return ""; + } + + if ($this->use_min_answers && $this->nr_min_answers > 0 && $this->nr_max_answers > 0 && $this->nr_min_answers == $this->nr_max_answers && count($entered_value) != $this->nr_max_answers) { + return sprintf($this->lng->txt("err_no_exact_answers"), $this->nr_min_answers); + } + if ($this->use_min_answers && $this->nr_min_answers > 0 && count($entered_value) < $this->nr_min_answers) { + return sprintf($this->lng->txt("err_no_min_answers"), $this->nr_min_answers); + } + if ($this->use_min_answers && $this->nr_max_answers > 0 && count($entered_value) > $this->nr_max_answers) { + return sprintf($this->lng->txt("err_no_max_answers"), $this->nr_max_answers); + } + if (!is_array($entered_value)) { + return $this->lng->txt("question_mr_not_checked"); + } + for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) { + $cat = $this->categories->getCategory($i); + if ($cat->other) { + if (in_array($i, $entered_value)) { + if (array_key_exists($this->getId() . "_" . $i . "_other", $post_data) && !strlen($post_data[$this->getId() . "_" . $i . "_other"])) { + return $this->lng->txt("question_mr_no_other_answer"); + } + } else { + if (strlen($post_data[$this->getId() . "_" . $i . "_other"])) { + return $this->lng->txt("question_mr_no_other_answer_checked"); + } + } + } + } + return ""; + } + + public function saveUserInput($post_data, $active_id, $a_return = false) + { + $ilDB = $this->db; + + if ($a_return) { + $return_data = array(); + } + if (is_array($post_data[$this->getId() . "_value"])) { + foreach ($post_data[$this->getId() . "_value"] as $entered_value) { + if (strlen($entered_value) > 0) { + if (!$a_return) { + $next_id = $ilDB->nextId('svy_answer'); + + #20216 + $fields = array(); + $fields['answer_id'] = array("integer", $next_id); + $fields['question_fi'] = array("integer", $this->getId()); + $fields['active_fi'] = array("integer", $active_id); + $fields['value'] = array("float", (strlen($entered_value)) ? $entered_value : null); + $fields['textanswer'] = array("clob", ($post_data[$this->getId() . "_" . $entered_value . "_other"]) ? $post_data[$this->getId() . "_" . $entered_value . "_other"] : null); + $fields['tstamp'] = array("integer", time()); + + $affectedRows = $ilDB->insert("svy_answer", $fields); + } else { + $return_data[] = array("value"=>$entered_value, + "textanswer"=>$post_data[$this->getId() . "_" . $entered_value . "_other"]); + } + } + } + } + if ($a_return) { + return $return_data; + } + } + + /** + * Import additional meta data from the question import file. Usually + * the meta data section is used to store question elements which are not + * part of the standard XML schema. + * + * @return array $a_meta Array containing the additional meta data + * @access public + */ + public function importAdditionalMetadata($a_meta) + { + foreach ($a_meta as $key => $value) { + switch ($value["label"]) { + case "orientation": + $this->setOrientation($value["entry"]); + break; + case "use_min_answers": + $this->use_min_answers = $value["entry"]; + break; + case "nr_min_answers": + $this->nr_min_answers = $value["entry"]; + break; + case "nr_max_answers": + $this->nr_max_answers = $value["entry"]; + break; + } + } + } + + /** + * Import response data from the question import file + * + * @return array $a_data Array containing the response data + * @access public + */ + public function importResponses($a_data) + { + foreach ($a_data as $id => $data) { + $categorytext = ""; + foreach ($data["material"] as $material) { + $categorytext .= $material["text"]; + } + $this->categories->addCategory( + $categorytext, + strlen($data['other']) ? $data['other'] : 0, + strlen($data['neutral']) ? $data['neutral'] : 0, + strlen($data['label']) ? $data['label'] : null, + strlen($data['scale']) ? $data['scale'] : null + ); + } + } + + /** + * Returns if the question is usable for preconditions + * + * @return boolean TRUE if the question is usable for a precondition, FALSE otherwise + * @access public + */ + public function usableForPrecondition() + { + return true; + } + + /** + * Returns the available relations for the question + * + * @return array An array containing the available relations + * @access public + */ + public function getAvailableRelations() + { + return array("=", "<>"); + } + + /** + * Returns the options for preconditions + * + * @return array + */ + public function getPreconditionOptions() + { + $lng = $this->lng; + + $options = array(); + for ($i = 0; $i < $this->categories->getCategoryCount(); $i++) { + $category = $this->categories->getCategory($i); + $options[$category->scale-1] = $category->scale . " - " . $category->title; + } + return $options; + } + + /** + * Creates a form property for the precondition value + * + * @return The ILIAS form element + * @access public + */ + public function getPreconditionSelectValue($default = "", $title, $variable) + { + include_once "./Services/Form/classes/class.ilSelectInputGUI.php"; + $step3 = new ilSelectInputGUI($title, $variable); + $options = $this->getPreconditionOptions(); + $step3->setOptions($options); + $step3->setValue($default); + return $step3; + } + + /** + * Returns the output for a precondition value + * + * @param string $value The precondition value + * @return string The output of the precondition value + * @access public + */ + public function getPreconditionValueOutput($value) + { + // #18136 + $category = $this->categories->getCategoryForScale($value+1); + + // #17895 - see getPreconditionOptions() + return $category->scale . + " - " . + ((strlen($category->title)) ? $category->title : $this->lng->txt('other_answer')); + } + + public function getCategories() + { + return $this->categories; + } } -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyMultipleChoiceQuestionEvaluation.php b/Modules/SurveyQuestionPool/classes/class.SurveyMultipleChoiceQuestionEvaluation.php index d0f9c297de99d47c6eba072789313cd497e63b8c..ab1c0c676742a39076f995c66dc1d40e9939e490 100644 --- a/Modules/SurveyQuestionPool/classes/class.SurveyMultipleChoiceQuestionEvaluation.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyMultipleChoiceQuestionEvaluation.php @@ -4,87 +4,74 @@ include_once "Modules/SurveyQuestionPool/classes/class.SurveyQuestionEvaluation.php"; /** - * Survey mc evaluation + * Survey mc evaluation * * @author Jörg Lützenkirchen$error_message
"); - } - if ($show_questiontext) - { - $this->outQuestionText($template); - } - if ($question_title) - { - $template->setVariable("QUESTION_TITLE", $this->object->getTitle()); - } - $template->parseCurrentBlock(); - return $template->get(); - } + foreach ($_POST['answers']['answer'] as $key => $value) { + if (strlen($value)) { + $this->object->getCategories()->addCategory($value, $_POST['answers']['other'][$key], 0, null, $_POST['answers']['scale'][$key]); + } + } + if (strlen($_POST['answers']['neutral'])) { + $this->object->getCategories()->addCategory($_POST['answers']['neutral'], 0, 1, null, $_POST['answers_neutral_scale']); + } + } + + public function getParsedAnswers(array $a_working_data = null, $a_only_user_anwers = false) + { + if (is_array($a_working_data)) { + $user_answers = $a_working_data; + } + + $options = array(); + for ($i = 0; $i < $this->object->categories->getCategoryCount(); $i++) { + $cat = $this->object->categories->getCategory($i); + $value = ($cat->scale) ? ($cat->scale - 1) : $i; + + $checked = "unchecked"; + $text = null; + if (is_array($a_working_data)) { + foreach ($user_answers as $user_answer) { + if ($value == $user_answer["value"]) { + $checked = "checked"; + if ($user_answer["textanswer"]) { + $text = $user_answer["textanswer"]; + } + break; + } + } + } + + // "other" options have to be last or horizontal will be screwed + $idx = $cat->other . "_" . $value; + + if (!$a_only_user_anwers || $checked == "checked") { + $options[$idx] = array( + "value" => $value + ,"title" => trim($cat->title) + ,"other" => (bool) $cat->other + ,"checked" => $checked + ,"textanswer" => $text + ); + } + + ksort($options); + } + + return array_values($options); + } + + /** + * Creates a HTML representation of the question + * + * @access private + */ + public function getPrintView($question_title = 1, $show_questiontext = 1, $survey_id = null, array $a_working_data = null) + { + $options = $this->getParsedAnswers($a_working_data); + + $template = new ilTemplate("tpl.il_svy_qpl_mc_printview.html", true, true, "Modules/SurveyQuestionPool"); + switch ($this->object->getOrientation()) { + case 0: + // vertical orientation + foreach ($options as $option) { + if ($option["other"]) { + $template->setCurrentBlock("other_row"); + $template->setVariable("IMAGE_CHECKBOX", ilUtil::getHtmlPath(ilUtil::getImagePath("checkbox_" . $option["checked"] . ".png"))); + $template->setVariable("ALT_CHECKBOX", $this->lng->txt($option["checked"])); + $template->setVariable("TITLE_CHECKBOX", $this->lng->txt($option["checked"])); + $template->setVariable("OTHER_LABEL", ilUtil::prepareFormOutput($option["title"])); + $template->setVariable("OTHER_ANSWER", $option["textanswer"] + ? ilUtil::prepareFormOutput($option["textanswer"]) + : " "); + $template->parseCurrentBlock(); + } else { + $template->setCurrentBlock("mc_row"); + $template->setVariable("IMAGE_CHECKBOX", ilUtil::getHtmlPath(ilUtil::getImagePath("checkbox_" . $option["checked"] . ".png"))); + $template->setVariable("ALT_CHECKBOX", $this->lng->txt($option["checked"])); + $template->setVariable("TITLE_CHECKBOX", $this->lng->txt($option["checked"])); + $template->setVariable("TEXT_MC", ilUtil::prepareFormOutput($option["title"])); + $template->parseCurrentBlock(); + } + } + break; + case 1: + // horizontal orientation + foreach ($options as $option) { + $template->setCurrentBlock("checkbox_col"); + $template->setVariable("IMAGE_CHECKBOX", ilUtil::getHtmlPath(ilUtil::getImagePath("checkbox_" . $option["checked"] . ".png"))); + $template->setVariable("ALT_CHECKBOX", $this->lng->txt($option["checked"])); + $template->setVariable("TITLE_CHECKBOX", $this->lng->txt($option["checked"])); + $template->parseCurrentBlock(); + } + foreach ($options as $option) { + if ($option["other"]) { + $template->setCurrentBlock("other_text_col"); + $template->setVariable("OTHER_LABEL", ilUtil::prepareFormOutput($option["title"])); + $template->setVariable("OTHER_ANSWER", $option["textanswer"] + ? ilUtil::prepareFormOutput($option["textanswer"]) + : " "); + $template->parseCurrentBlock(); + } else { + $template->setCurrentBlock("text_col"); + $template->setVariable("TEXT_MC", ilUtil::prepareFormOutput($option["title"])); + $template->parseCurrentBlock(); + } + } + break; + } + + if ($this->object->use_min_answers) { + $template->setCurrentBlock('min_max_msg'); + if ($this->object->nr_min_answers > 0 && $this->object->nr_max_answers > 0) { + $template->setVariable('MIN_MAX_MSG', sprintf($this->lng->txt('msg_min_max_nr_answers'), $this->object->nr_min_answers, $this->object->nr_max_answers)); + } elseif ($this->object->nr_min_answers > 0) { + $template->setVariable('MIN_MAX_MSG', sprintf($this->lng->txt('msg_min_nr_answers'), $this->object->nr_min_answers)); + } elseif ($this->object->nr_max_answers > 0) { + $template->setVariable('MIN_MAX_MSG', sprintf($this->lng->txt('msg_max_nr_answers'), $this->object->nr_max_answers)); + } + $template->parseCurrentBlock(); + } + if ($show_questiontext) { + $this->outQuestionText($template); + } + if ($question_title) { + $template->setVariable("QUESTION_TITLE", $this->getPrintViewQuestionTitle($question_title)); + } + $template->parseCurrentBlock(); + return $template->get(); + } + + + // + // EXECUTION + // + + /** + * Creates the question output form for the learner + * + * @access public + */ + public function getWorkingForm($working_data = "", $question_title = 1, $show_questiontext = 1, $error_message = "", $survey_id = null) + { + $template = new ilTemplate("tpl.il_svy_out_mc.html", true, true, "Modules/SurveyQuestionPool"); + $template->setCurrentBlock("material"); + $template->setVariable("TEXT_MATERIAL", $this->getMaterialOutput()); + $template->parseCurrentBlock(); + switch ($this->object->getOrientation()) { + case 0: + // vertical orientation + for ($i = 0; $i < $this->object->categories->getCategoryCount(); $i++) { + $cat = $this->object->categories->getCategory($i); + if ($cat->other) { + $template->setCurrentBlock("other_row"); + if (strlen($cat->title)) { + $template->setVariable("OTHER_LABEL", $cat->title); + } + $template->setVariable("VALUE_MC", ($cat->scale) ? ($cat->scale - 1) : $i); + $template->setVariable("QUESTION_ID", $this->object->getId()); + if (is_array($working_data)) { + foreach ($working_data as $value) { + if (strlen($value["value"])) { + if ($value["value"] == $cat->scale-1) { + $template->setVariable("OTHER_VALUE", ' value="' . ilUtil::prepareFormOutput($value['textanswer']) . '"'); + if (!$value['uncheck']) { + $template->setVariable("CHECKED_MC", " checked=\"checked\""); + } + } + } + } + } + $template->parseCurrentBlock(); + } else { + $template->setCurrentBlock("mc_row"); + if ($cat->neutral) { + $template->setVariable('ROWCLASS', ' class="neutral"'); + } + $template->setVariable("TEXT_MC", ilUtil::prepareFormOutput($cat->title)); + $template->setVariable("VALUE_MC", ($cat->scale) ? ($cat->scale - 1) : $i); + $template->setVariable("QUESTION_ID", $this->object->getId()); + if (is_array($working_data)) { + foreach ($working_data as $value) { + if (strlen($value["value"])) { + if ($value["value"] == $cat->scale-1) { + if (!$value['uncheck']) { + $template->setVariable("CHECKED_MC", " checked=\"checked\""); + } + } + } + } + } + $template->parseCurrentBlock(); + } + $template->touchBlock('outer_row'); + } + break; + case 1: + // horizontal orientation + + // #15477 - reverting the categorizing of answers + for ($i = 0; $i < $this->object->categories->getCategoryCount(); $i++) { + $cat = $this->object->categories->getCategory($i); + + // checkbox + $template->setCurrentBlock("checkbox_col"); + if ($cat->neutral) { + $template->setVariable('COLCLASS', ' neutral'); + } + $template->setVariable("VALUE_MC", ($cat->scale) ? ($cat->scale - 1) : $i); + $template->setVariable("QUESTION_ID", $this->object->getId()); + if (is_array($working_data)) { + foreach ($working_data as $value) { + if (strlen($value["value"])) { + if ($value["value"] == $cat->scale-1) { + if (!$value['uncheck']) { + $template->setVariable("CHECKED_MC", " checked=\"checked\""); + } + } + } + } + } + $template->parseCurrentBlock(); + + // answer & input + if ($cat->other) { + $template->setCurrentBlock("text_other_col"); + $template->setVariable("VALUE_MC", ($cat->scale) ? ($cat->scale - 1) : $i); + $template->setVariable("QUESTION_ID", $this->object->getId()); + if (strlen($cat->title)) { + $template->setVariable("OTHER_LABEL", $cat->title); + } + if (is_array($working_data)) { + foreach ($working_data as $value) { + if (strlen($value["value"])) { + if ($value["value"] == $cat->scale-1) { + $template->setVariable("OTHER_VALUE", ' value="' . ilUtil::prepareFormOutput($value['textanswer']) . '"'); + } + } + } + } + $template->parseCurrentBlock(); + } + // answer + else { + $template->setCurrentBlock("text_col"); + if ($cat->neutral) { + $template->setVariable('COLCLASS', ' neutral'); + } + $template->setVariable("VALUE_MC", ($cat->scale) ? ($cat->scale - 1) : $i); + $template->setVariable("TEXT_MC", ilUtil::prepareFormOutput($cat->title)); + $template->setVariable("QUESTION_ID", $this->object->getId()); + $template->parseCurrentBlock(); + } + $template->touchBlock('text_outer_col'); + } + break; + } + + $template->setCurrentBlock("question_data"); + if ($this->object->use_min_answers) { + $template->setCurrentBlock('min_max_msg'); + if ($this->object->nr_min_answers > 0 && $this->object->nr_max_answers > 0) { + if ($this->object->nr_min_answers == $this->object->nr_max_answers) { + $template->setVariable('MIN_MAX_MSG', sprintf($this->lng->txt('msg_min_max_exact_answers'), $this->object->nr_min_answers)); + } else { + $template->setVariable('MIN_MAX_MSG', sprintf($this->lng->txt('msg_min_max_nr_answers'), $this->object->nr_min_answers, $this->object->nr_max_answers)); + } + } elseif ($this->object->nr_min_answers > 0) { + $template->setVariable('MIN_MAX_MSG', sprintf($this->lng->txt('msg_min_nr_answers'), $this->object->nr_min_answers)); + } elseif ($this->object->nr_max_answers > 0) { + $template->setVariable('MIN_MAX_MSG', sprintf($this->lng->txt('msg_max_nr_answers'), $this->object->nr_max_answers)); + } + $template->parseCurrentBlock(); + } + if (strcmp($error_message, "") != 0) { + $template->setVariable("ERROR_MESSAGE", "$error_message
"); + } + if ($show_questiontext) { + $this->outQuestionText($template); + } + if ($question_title) { + $template->setVariable("QUESTION_TITLE", $this->object->getTitle()); + } + $template->parseCurrentBlock(); + return $template->get(); + } } - -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php b/Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php index 15aa9936e176a424a871a432d562744c88d53e57..2e7b8ed191925e2a3521f4ab6fa2973c430ebaa2 100755 --- a/Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php @@ -33,2210 +33,2124 @@ */ class SurveyQuestion { - /** - * @var ilObjUser - */ - protected $user; - - /** - * @var ilDB - */ - protected $db; - - /** - * A unique question id - * - * @var integer - */ - var $id; - - /** - * A title string to describe the question - * - * @var string - */ - var $title; - /** - * A description string to describe the question more detailed as the title - * - * @var string - */ - var $description; - /** - * A unique positive numerical ID which identifies the owner/creator of the question. - * This can be a primary key from a database table for example. - * - * @var integer - */ - var $owner; - - /** - * A text representation of the authors name. The name of the author must - * not necessary be the name of the owner. - * - * @var string - */ - var $author; - - /** - * Contains uris name and uris to additional materials - * - * @var array - */ - var $materials; - - /** - * The database id of a survey in which the question is contained - * - * @var integer - */ - var $survey_id; - - /** - * Object id of the container object - * - * @var double - */ - var $obj_id; - - /** - * Questiontext string - * - * @var string - */ - var $questiontext; - - /** - * Contains the obligatory state of the question - * - * @var boolean - */ - var $obligatory; - - /** - * The reference to the Language class - * - * @var object - */ - var $lng; - - /** - * The orientation of the question output (0 = vertical, 1 = horizontal) - * - * @var integer - */ - var $orientation; - - var $material; - var $complete; - - /** - * An array containing the cumulated results of the question for a given survey - */ - protected $cumulated; - - /** - * data array containing the question data - */ - private $arrData; - - /** - * @var ilLogger - */ - protected $log; - - /** - * SurveyQuestion constructor - * The constructor takes possible arguments an creates an instance of the SurveyQuestion object. - * - * @param string $title A title string to describe the question - * @param string $description A description string to describe the question - * @param string $author A string containing the name of the questions author - * @param integer $owner A numerical ID to identify the owner/creator - * @access public - */ - function __construct($title = "", $description = "", $author = "", $questiontext = "", $owner = -1) - { - global $DIC; - - $this->user = $DIC->user(); - $this->db = $DIC->database(); - $lng = $DIC->language(); - $ilUser = $DIC->user(); - - $this->lng = $lng; - $this->complete = 0; - $this->title = $title; - $this->description = $description; - $this->questiontext = $questiontext; - $this->author = $author; - $this->cumulated = array(); - if (!$this->author) - { - $this->author = $ilUser->fullname; - } - $this->owner = $owner; - if ($this->owner == -1) - { - $this->owner = $ilUser->getId(); - } - $this->id = -1; - $this->survey_id = -1; - $this->obligatory = 1; - $this->orientation = 0; - $this->materials = array(); - $this->material = array(); - $this->arrData = array(); - - $this->log = ilLoggerFactory::getLogger('svy'); - } - - /** - * Sets the complete state of the question - * - * @param integer $a_complete 1 if complete, 0 otherwise - * @access public - */ - function setComplete($a_complete) - { - $this->complete = ($a_complete) ? 1 : 0; - } - - /** - * Returns 1, if a question is complete for use - * - * @return integer 1, if the question is complete for use, otherwise 0 - * @access public - */ - function isComplete() - { - return 0; - } - - /** - * Returns TRUE if the question title exists in the database - * - * @param string $title The title of the question - * @param string $questionpool_reference The reference id of a container question pool - * @return boolean The result of the title check - * @access public - */ - function questionTitleExists($title, $questionpool_object = "") - { - $ilDB = $this->db; - - $refwhere = ""; - if (strcmp($questionpool_object, "") != 0) - { - $refwhere = sprintf(" AND obj_fi = %s", - $ilDB->quote($questionpool_object, 'integer') - ); - } - $result = $ilDB->queryF("SELECT question_id FROM svy_question WHERE title = %s$refwhere", - array('text'), - array($title) - ); - return ($result->numRows() > 0) ? true : false; - } - - /** - * Sets the title string of the SurveyQuestion object - * - * @param string $title A title string to describe the question - * @access public - * @see $title - */ - function setTitle($title = "") - { - $this->title = $title; - } - - /** - * Sets the obligatory state of the question - * - * @param integer $obligatory 1, if the question is obligatory, otherwise 0 - * @access public - * @see $obligatory - */ - function setObligatory($obligatory = 1) - { - $this->obligatory = ($obligatory) ? 1 : 0; - } - - /** - * Sets the orientation of the question output - * - * @param integer $orientation 0 = vertical, 1 = horizontal - * @access public - * @see $orientation - */ - function setOrientation($orientation = 0) - { - $this->orientation = ($orientation) ? $orientation : 0; - } - - /** - * Sets the id of the SurveyQuestion object - * - * @param integer $id A unique integer value - * @access public - * @see $id - */ - function setId($id = -1) - { - $this->id = $id; - } - - /** - * Sets the survey id of the SurveyQuestion object - * - * @param integer $id A unique integer value - * @access public - * @see $survey_id - */ - function setSurveyId($id = -1) - { - $this->survey_id = $id; - } - - /** - * Sets the description string of the SurveyQuestion object - * - * @param string $description A description string to describe the question - * @access public - * @see $description - */ - function setDescription($description = "") - { - $this->description = $description; - } - - /** - * Sets the materials uri - * - * @param string $materials_file An uri to additional materials - * @param string $materials_name An uri name to additional materials - * @access public - * @see $materials - */ - function addMaterials($materials_file, $materials_name="") - { - if (empty($materials_name)) - { - $materials_name = $materials_file; - } - if ((!empty($materials_name))&&(!array_key_exists($materials_name, $this->materials))) - { - $this->materials[$materials_name] = $materials_file; - } - } - - /** - * Sets and uploads the materials uri - * - * @param string $materials_filename, string $materials_tempfilename, string $materials - * @access public - * @see $materials - */ - function setMaterialsfile($materials_filename, $materials_tempfilename="", $materials_name="") - { - if (!empty($materials_filename)) - { - $materialspath = $this->getMaterialsPath(); - if (!file_exists($materialspath)) - { - ilUtil::makeDirParents($materialspath); - } - if (ilUtil::moveUploadedFile($materials_tempfilename, $materials_filename, - $materialspath.$materials_filename)) - { - print "image not uploaded!!!! "; - } - else - { - $this->addMaterials($materials_filename, $materials_name); - } - } - } - - /** - * Deletes a materials uri with a given name. - * - * @param string $index A materials_name of the materials uri - * @access public - * @see $materials - */ - function deleteMaterial($materials_name = "") - { - foreach ($this->materials as $key => $value) - { - if (strcmp($key, $materials_name)==0) - { - if (file_exists($this->getMaterialsPath().$value)) - { - unlink($this->getMaterialsPath().$value); - } - unset($this->materials[$key]); - } - } - } - - /** - * Deletes all materials uris - * - * @access public - * @see $materials - */ - function flushMaterials() - { - $this->materials = array(); - } - - /** - * Sets the authors name of the SurveyQuestion object - * - * @param string $author A string containing the name of the questions author - * @access public - * @see $author - */ - function setAuthor($author = "") - { - $ilUser = $this->user; - - if (!$author) - { - $author = $ilUser->fullname; - } - $this->author = $author; - } - - /** - * Sets the questiontext of the SurveyQuestion object - * - * @param string $questiontext A string containing the questiontext - * @access public - * @see $questiontext - */ - function setQuestiontext($questiontext = "") - { - $this->questiontext = $questiontext; - } - - /** - * Sets the creator/owner ID of the SurveyQuestion object - * - * @param integer $owner A numerical ID to identify the owner/creator - * @access public - * @see $owner - */ - function setOwner($owner = "") - { - $this->owner = $owner; - } - - /** - * Gets the title string of the SurveyQuestion object - * - * @return string The title string to describe the question - * @access public - * @see $title - */ - function getTitle() - { - return $this->title; - } - - function getLabel() - { - return $this->label; - } - - /** - * Gets the id of the SurveyQuestion object - * - * @return integer The id of the SurveyQuestion object - * @access public - * @see $id - */ - function getId() - { - return $this->id; - } - - /** - * Gets the obligatory state of the question - * - * @return integer 1, if the question is obligatory, otherwise 0 - * @see $obligatory - */ - public function getObligatory($survey_id = "") - { - return ($this->obligatory) ? 1 : 0; - } - - /** - * Gets the survey id of the SurveyQuestion object - * - * @return integer The survey id of the SurveyQuestion object - * @access public - * @see $survey_id - */ - function getSurveyId() - { - return $this->survey_id; - } - - /** - * Gets the orientation of the question output - * - * @return integer 0 = vertical, 1 = horizontal - * @access public - * @see $orientation - */ - function getOrientation() - { - switch ($this->orientation) - { - case 0: - case 1: - case 2: - break; - default: - $this->orientation = 0; - break; - } - return $this->orientation; - } - - - /** - * Gets the description string of the SurveyQuestion object - * - * @return string The description string to describe the question - * @access public - * @see $description - */ - function getDescription() - { - return (strlen($this->description)) ? $this->description : NULL; - } - - /** - * Gets the authors name of the SurveyQuestion object - * - * @return string The string containing the name of the questions author - * @access public - * @see $author - */ - function getAuthor() - { - return (strlen($this->author)) ? $this->author : NULL; - } - - /** - * Gets the creator/owner ID of the SurveyQuestion object - * - * @return integer The numerical ID to identify the owner/creator - * @access public - * @see $owner - */ - function getOwner() - { - return $this->owner; - } - - /** - * Gets the questiontext of the SurveyQuestion object - * - * @return string The questiontext of the question object - * @access public - * @see $questiontext - */ - function getQuestiontext() - { - return (strlen($this->questiontext)) ? $this->questiontext : NULL; - } - - /** - * Get the reference id of the container object - * - * @return integer The reference id of the container object - * @access public - * @see $obj_id - */ - function getObjId() { - return $this->obj_id; - } - - /** - * Set the reference id of the container object - * - * @param integer $obj_id The reference id of the container object - * @access public - * @see $obj_id - */ - function setObjId($obj_id = 0) - { - $this->obj_id = $obj_id; - } - - /** - * Duplicates a survey question - * - * @access public - */ - function duplicate($for_survey = true, $title = "", $author = "", $owner = "", $a_survey_id = 0) - { - if ($this->getId() <= 0) - { - // The question has not been saved. It cannot be duplicated - return; - } - // duplicate the question in database - $clone = $this; - $original_id = $this->getId(); - $clone->setId(-1); - if ($a_survey_id > 0) - { - $clone->setObjId($a_survey_id); - } - if ($title) - { - $clone->setTitle($title); - } - if ($author) - { - $clone->setAuthor($author); - } - if ($owner) - { - $clone->setOwner($owner); - } - if ($for_survey) - { - $clone->saveToDb($original_id); - } - else - { - $clone->saveToDb(); - } - // duplicate the materials - $clone->duplicateMaterials($original_id); - // copy XHTML media objects - $clone->copyXHTMLMediaObjectsOfQuestion($original_id); - return $clone->getId(); - } - - /** - * Copies an assOrderingQuestion object - * - * @access public - */ - function copyObject($target_questionpool, $title = "") - { - if ($this->getId() <= 0) - { - // The question has not been saved. It cannot be copied - return; - } - $clone = $this; - $original_id = self::_getOriginalId($this->getId(), false); - $clone->setId(-1); - $source_questionpool = $this->getObjId(); - $clone->setObjId($target_questionpool); - if ($title) - { - $clone->setTitle($title); - } - - $clone->saveToDb(); - - // duplicate the materials - $clone->duplicateMaterials($original_id); - // copy XHTML media objects - $clone->copyXHTMLMediaObjectsOfQuestion($original_id); - return $clone->getId(); - } - - /** - * Increases the media object usage counter when a question is duplicated - * - * @param integer $a_q_id The question id of the original question - * @access public - */ - function copyXHTMLMediaObjectsOfQuestion($a_q_id) - { - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mobs = ilObjMediaObject::_getMobsOfObject("spl:html", $a_q_id); - foreach ($mobs as $mob) - { - ilObjMediaObject::_saveUsage($mob, "spl:html", $this->getId()); - } - } - - /** - * Loads a SurveyQuestion object from the database - * - * @param integer $question_id A unique key which defines the question in the database - * @access public - */ - function loadFromDb($question_id) - { - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT * FROM svy_material WHERE question_fi = %s", - array('integer'), - array($this->getId()) - ); - $this->material = array(); - if ($result->numRows()) - { - include_once "./Modules/SurveyQuestionPool/classes/class.ilSurveyMaterial.php"; - while ($row = $ilDB->fetchAssoc($result)) - { - $mat = new ilSurveyMaterial(); - $mat->type = $row['material_type']; - $mat->internal_link = $row['internal_link']; - $mat->title = $row['material_title']; - $mat->import_id = $row['import_id']; - $mat->text_material = $row['text_material']; - $mat->external_link = $row['external_link']; - $mat->file_material = $row['file_material']; - array_push($this->material, $mat); - } - } - } - - /** - * Checks whether the question is complete or not - * - * @return boolean TRUE if the question is complete, FALSE otherwise - * @access public - */ - static function _isComplete($question_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $result = $ilDB->queryF("SELECT complete FROM svy_question WHERE question_id = %s", - array('integer'), - array($question_id) - ); - if ($result->numRows()) - { - $row = $ilDB->fetchAssoc($result); - if ($row["complete"] == 1) - { - return TRUE; - } - } - return FALSE; - } - - /** - * Saves the complete flag to the database - * - * @access public - */ - function saveCompletionStatus($original_id = "") - { - $ilDB = $this->db; - - $question_id = $this->getId(); - if (strlen($original_id)) - { - $question_id = $original_id; - } - - if ($this->getId() > 0) - { - $this->log->debug("UPDATE svy_question question_id=".$question_id); - - // update existing dataset - $affectedRows = $ilDB->manipulateF("UPDATE svy_question SET complete = %s, tstamp = %s WHERE question_id = %s", - array('text', 'integer', 'integer'), - array($this->isComplete(), time(), $question_id) - ); - } - } - - /** - * Saves a SurveyQuestion object to a database - * - * @param integer $original_id - * @access public - */ - function saveToDb($original_id = "") - { - $ilDB = $this->db; - - // cleanup RTE images which are not inserted into the question text - include_once("./Services/RTE/classes/class.ilRTE.php"); - ilRTE::_cleanupMediaObjectUsage($this->getQuestiontext(), "spl:html", $this->getId()); - $affectedRows = 0; - if ($this->getId() == -1) - { + /** + * @var ilObjUser + */ + protected $user; + + /** + * @var ilDB + */ + protected $db; + + /** + * A unique question id + * + * @var integer + */ + public $id; + + /** + * A title string to describe the question + * + * @var string + */ + public $title; + /** + * A description string to describe the question more detailed as the title + * + * @var string + */ + public $description; + /** + * A unique positive numerical ID which identifies the owner/creator of the question. + * This can be a primary key from a database table for example. + * + * @var integer + */ + public $owner; + + /** + * A text representation of the authors name. The name of the author must + * not necessary be the name of the owner. + * + * @var string + */ + public $author; + + /** + * Contains uris name and uris to additional materials + * + * @var array + */ + public $materials; + + /** + * The database id of a survey in which the question is contained + * + * @var integer + */ + public $survey_id; + + /** + * Object id of the container object + * + * @var double + */ + public $obj_id; + + /** + * Questiontext string + * + * @var string + */ + public $questiontext; + + /** + * Contains the obligatory state of the question + * + * @var boolean + */ + public $obligatory; + + /** + * The reference to the Language class + * + * @var object + */ + public $lng; + + /** + * The orientation of the question output (0 = vertical, 1 = horizontal) + * + * @var integer + */ + public $orientation; + + public $material; + public $complete; + + /** + * An array containing the cumulated results of the question for a given survey + */ + protected $cumulated; + + /** + * data array containing the question data + */ + private $arrData; + + /** + * @var ilLogger + */ + protected $log; + + /** + * SurveyQuestion constructor + * The constructor takes possible arguments an creates an instance of the SurveyQuestion object. + * + * @param string $title A title string to describe the question + * @param string $description A description string to describe the question + * @param string $author A string containing the name of the questions author + * @param integer $owner A numerical ID to identify the owner/creator + * @access public + */ + public function __construct($title = "", $description = "", $author = "", $questiontext = "", $owner = -1) + { + global $DIC; + + $this->user = $DIC->user(); + $this->db = $DIC->database(); + $lng = $DIC->language(); + $ilUser = $DIC->user(); + + $this->lng = $lng; + $this->complete = 0; + $this->title = $title; + $this->description = $description; + $this->questiontext = $questiontext; + $this->author = $author; + $this->cumulated = array(); + if (!$this->author) { + $this->author = $ilUser->fullname; + } + $this->owner = $owner; + if ($this->owner == -1) { + $this->owner = $ilUser->getId(); + } + $this->id = -1; + $this->survey_id = -1; + $this->obligatory = 1; + $this->orientation = 0; + $this->materials = array(); + $this->material = array(); + $this->arrData = array(); + + $this->log = ilLoggerFactory::getLogger('svy'); + } + + /** + * Sets the complete state of the question + * + * @param integer $a_complete 1 if complete, 0 otherwise + * @access public + */ + public function setComplete($a_complete) + { + $this->complete = ($a_complete) ? 1 : 0; + } + + /** + * Returns 1, if a question is complete for use + * + * @return integer 1, if the question is complete for use, otherwise 0 + * @access public + */ + public function isComplete() + { + return 0; + } + + /** + * Returns TRUE if the question title exists in the database + * + * @param string $title The title of the question + * @param string $questionpool_reference The reference id of a container question pool + * @return boolean The result of the title check + * @access public + */ + public function questionTitleExists($title, $questionpool_object = "") + { + $ilDB = $this->db; + + $refwhere = ""; + if (strcmp($questionpool_object, "") != 0) { + $refwhere = sprintf( + " AND obj_fi = %s", + $ilDB->quote($questionpool_object, 'integer') + ); + } + $result = $ilDB->queryF( + "SELECT question_id FROM svy_question WHERE title = %s$refwhere", + array('text'), + array($title) + ); + return ($result->numRows() > 0) ? true : false; + } + + /** + * Sets the title string of the SurveyQuestion object + * + * @param string $title A title string to describe the question + * @access public + * @see $title + */ + public function setTitle($title = "") + { + $this->title = $title; + } + + /** + * Sets the obligatory state of the question + * + * @param integer $obligatory 1, if the question is obligatory, otherwise 0 + * @access public + * @see $obligatory + */ + public function setObligatory($obligatory = 1) + { + $this->obligatory = ($obligatory) ? 1 : 0; + } + + /** + * Sets the orientation of the question output + * + * @param integer $orientation 0 = vertical, 1 = horizontal + * @access public + * @see $orientation + */ + public function setOrientation($orientation = 0) + { + $this->orientation = ($orientation) ? $orientation : 0; + } + + /** + * Sets the id of the SurveyQuestion object + * + * @param integer $id A unique integer value + * @access public + * @see $id + */ + public function setId($id = -1) + { + $this->id = $id; + } + + /** + * Sets the survey id of the SurveyQuestion object + * + * @param integer $id A unique integer value + * @access public + * @see $survey_id + */ + public function setSurveyId($id = -1) + { + $this->survey_id = $id; + } + + /** + * Sets the description string of the SurveyQuestion object + * + * @param string $description A description string to describe the question + * @access public + * @see $description + */ + public function setDescription($description = "") + { + $this->description = $description; + } + + /** + * Sets the materials uri + * + * @param string $materials_file An uri to additional materials + * @param string $materials_name An uri name to additional materials + * @access public + * @see $materials + */ + public function addMaterials($materials_file, $materials_name="") + { + if (empty($materials_name)) { + $materials_name = $materials_file; + } + if ((!empty($materials_name))&&(!array_key_exists($materials_name, $this->materials))) { + $this->materials[$materials_name] = $materials_file; + } + } + + /** + * Sets and uploads the materials uri + * + * @param string $materials_filename, string $materials_tempfilename, string $materials + * @access public + * @see $materials + */ + public function setMaterialsfile($materials_filename, $materials_tempfilename="", $materials_name="") + { + if (!empty($materials_filename)) { + $materialspath = $this->getMaterialsPath(); + if (!file_exists($materialspath)) { + ilUtil::makeDirParents($materialspath); + } + if (ilUtil::moveUploadedFile( + $materials_tempfilename, + $materials_filename, + $materialspath . $materials_filename + )) { + print "image not uploaded!!!! "; + } else { + $this->addMaterials($materials_filename, $materials_name); + } + } + } + + /** + * Deletes a materials uri with a given name. + * + * @param string $index A materials_name of the materials uri + * @access public + * @see $materials + */ + public function deleteMaterial($materials_name = "") + { + foreach ($this->materials as $key => $value) { + if (strcmp($key, $materials_name)==0) { + if (file_exists($this->getMaterialsPath() . $value)) { + unlink($this->getMaterialsPath() . $value); + } + unset($this->materials[$key]); + } + } + } + + /** + * Deletes all materials uris + * + * @access public + * @see $materials + */ + public function flushMaterials() + { + $this->materials = array(); + } + + /** + * Sets the authors name of the SurveyQuestion object + * + * @param string $author A string containing the name of the questions author + * @access public + * @see $author + */ + public function setAuthor($author = "") + { + $ilUser = $this->user; + + if (!$author) { + $author = $ilUser->fullname; + } + $this->author = $author; + } + + /** + * Sets the questiontext of the SurveyQuestion object + * + * @param string $questiontext A string containing the questiontext + * @access public + * @see $questiontext + */ + public function setQuestiontext($questiontext = "") + { + $this->questiontext = $questiontext; + } + + /** + * Sets the creator/owner ID of the SurveyQuestion object + * + * @param integer $owner A numerical ID to identify the owner/creator + * @access public + * @see $owner + */ + public function setOwner($owner = "") + { + $this->owner = $owner; + } + + /** + * Gets the title string of the SurveyQuestion object + * + * @return string The title string to describe the question + * @access public + * @see $title + */ + public function getTitle() + { + return $this->title; + } + + public function getLabel() + { + return $this->label; + } + + /** + * Gets the id of the SurveyQuestion object + * + * @return integer The id of the SurveyQuestion object + * @access public + * @see $id + */ + public function getId() + { + return $this->id; + } + + /** + * Gets the obligatory state of the question + * + * @return integer 1, if the question is obligatory, otherwise 0 + * @see $obligatory + */ + public function getObligatory($survey_id = "") + { + return ($this->obligatory) ? 1 : 0; + } + + /** + * Gets the survey id of the SurveyQuestion object + * + * @return integer The survey id of the SurveyQuestion object + * @access public + * @see $survey_id + */ + public function getSurveyId() + { + return $this->survey_id; + } + + /** + * Gets the orientation of the question output + * + * @return integer 0 = vertical, 1 = horizontal + * @access public + * @see $orientation + */ + public function getOrientation() + { + switch ($this->orientation) { + case 0: + case 1: + case 2: + break; + default: + $this->orientation = 0; + break; + } + return $this->orientation; + } + + + /** + * Gets the description string of the SurveyQuestion object + * + * @return string The description string to describe the question + * @access public + * @see $description + */ + public function getDescription() + { + return (strlen($this->description)) ? $this->description : null; + } + + /** + * Gets the authors name of the SurveyQuestion object + * + * @return string The string containing the name of the questions author + * @access public + * @see $author + */ + public function getAuthor() + { + return (strlen($this->author)) ? $this->author : null; + } + + /** + * Gets the creator/owner ID of the SurveyQuestion object + * + * @return integer The numerical ID to identify the owner/creator + * @access public + * @see $owner + */ + public function getOwner() + { + return $this->owner; + } + + /** + * Gets the questiontext of the SurveyQuestion object + * + * @return string The questiontext of the question object + * @access public + * @see $questiontext + */ + public function getQuestiontext() + { + return (strlen($this->questiontext)) ? $this->questiontext : null; + } + + /** + * Get the reference id of the container object + * + * @return integer The reference id of the container object + * @access public + * @see $obj_id + */ + public function getObjId() + { + return $this->obj_id; + } + + /** + * Set the reference id of the container object + * + * @param integer $obj_id The reference id of the container object + * @access public + * @see $obj_id + */ + public function setObjId($obj_id = 0) + { + $this->obj_id = $obj_id; + } + + /** + * Duplicates a survey question + * + * @access public + */ + public function duplicate($for_survey = true, $title = "", $author = "", $owner = "", $a_survey_id = 0) + { + if ($this->getId() <= 0) { + // The question has not been saved. It cannot be duplicated + return; + } + // duplicate the question in database + $clone = $this; + $original_id = $this->getId(); + $clone->setId(-1); + if ($a_survey_id > 0) { + $clone->setObjId($a_survey_id); + } + if ($title) { + $clone->setTitle($title); + } + if ($author) { + $clone->setAuthor($author); + } + if ($owner) { + $clone->setOwner($owner); + } + if ($for_survey) { + $clone->saveToDb($original_id); + } else { + $clone->saveToDb(); + } + // duplicate the materials + $clone->duplicateMaterials($original_id); + // copy XHTML media objects + $clone->copyXHTMLMediaObjectsOfQuestion($original_id); + return $clone->getId(); + } + + /** + * Copies an assOrderingQuestion object + * + * @access public + */ + public function copyObject($target_questionpool, $title = "") + { + if ($this->getId() <= 0) { + // The question has not been saved. It cannot be copied + return; + } + $clone = $this; + $original_id = self::_getOriginalId($this->getId(), false); + $clone->setId(-1); + $source_questionpool = $this->getObjId(); + $clone->setObjId($target_questionpool); + if ($title) { + $clone->setTitle($title); + } + + $clone->saveToDb(); + + // duplicate the materials + $clone->duplicateMaterials($original_id); + // copy XHTML media objects + $clone->copyXHTMLMediaObjectsOfQuestion($original_id); + return $clone->getId(); + } + + /** + * Increases the media object usage counter when a question is duplicated + * + * @param integer $a_q_id The question id of the original question + * @access public + */ + public function copyXHTMLMediaObjectsOfQuestion($a_q_id) + { + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mobs = ilObjMediaObject::_getMobsOfObject("spl:html", $a_q_id); + foreach ($mobs as $mob) { + ilObjMediaObject::_saveUsage($mob, "spl:html", $this->getId()); + } + } + + /** + * Loads a SurveyQuestion object from the database + * + * @param integer $question_id A unique key which defines the question in the database + * @access public + */ + public function loadFromDb($question_id) + { + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT * FROM svy_material WHERE question_fi = %s", + array('integer'), + array($this->getId()) + ); + $this->material = array(); + if ($result->numRows()) { + include_once "./Modules/SurveyQuestionPool/classes/class.ilSurveyMaterial.php"; + while ($row = $ilDB->fetchAssoc($result)) { + $mat = new ilSurveyMaterial(); + $mat->type = $row['material_type']; + $mat->internal_link = $row['internal_link']; + $mat->title = $row['material_title']; + $mat->import_id = $row['import_id']; + $mat->text_material = $row['text_material']; + $mat->external_link = $row['external_link']; + $mat->file_material = $row['file_material']; + array_push($this->material, $mat); + } + } + } + + /** + * Checks whether the question is complete or not + * + * @return boolean TRUE if the question is complete, FALSE otherwise + * @access public + */ + public static function _isComplete($question_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $result = $ilDB->queryF( + "SELECT complete FROM svy_question WHERE question_id = %s", + array('integer'), + array($question_id) + ); + if ($result->numRows()) { + $row = $ilDB->fetchAssoc($result); + if ($row["complete"] == 1) { + return true; + } + } + return false; + } + + /** + * Saves the complete flag to the database + * + * @access public + */ + public function saveCompletionStatus($original_id = "") + { + $ilDB = $this->db; + + $question_id = $this->getId(); + if (strlen($original_id)) { + $question_id = $original_id; + } + + if ($this->getId() > 0) { + $this->log->debug("UPDATE svy_question question_id=" . $question_id); + + // update existing dataset + $affectedRows = $ilDB->manipulateF( + "UPDATE svy_question SET complete = %s, tstamp = %s WHERE question_id = %s", + array('text', 'integer', 'integer'), + array($this->isComplete(), time(), $question_id) + ); + } + } + + /** + * Saves a SurveyQuestion object to a database + * + * @param integer $original_id + * @access public + */ + public function saveToDb($original_id = "") + { + $ilDB = $this->db; + + // cleanup RTE images which are not inserted into the question text + include_once("./Services/RTE/classes/class.ilRTE.php"); + ilRTE::_cleanupMediaObjectUsage($this->getQuestiontext(), "spl:html", $this->getId()); + $affectedRows = 0; + if ($this->getId() == -1) { // Write new dataset - $next_id = $ilDB->nextId('svy_question'); - $affectedRows = $ilDB->insert("svy_question", array( - "question_id" => array("integer", $next_id), - "questiontype_fi" => array("integer", $this->getQuestionTypeID()), - "obj_fi" => array("integer", $this->getObjId()), - "owner_fi" => array("integer", $this->getOwner()), - "title" => array("text", $this->getTitle()), - "label" => array("text", (strlen($this->label)) ? $this->label : null), - "description" => array("text", $this->getDescription()), - "author" => array("text", $this->getAuthor()), - "questiontext" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getQuestiontext(), 0)), - "obligatory" => array("text", $this->getObligatory()), - "complete" => array("text", $this->isComplete()), - "created" => array("integer", time()), - "original_id" => array("integer", ($original_id) ? $original_id : NULL), - "tstamp" => array("integer", time()) - )); - - //$this->log->debug("INSERT: svy_question id=".$next_id." questiontype_fi=".$this->getQuestionTypeID()." obj_fi".$this->getObjId()." title=".$this->getTitle()." ..."); - - $this->setId($next_id); - } - else - { - // update existing dataset - $affectedRows = $ilDB->update("svy_question", array( - "title" => array("text", $this->getTitle()), - "label" => array("text", (strlen($this->label)) ? $this->label : null), - "description" => array("text", $this->getDescription()), - "author" => array("text", $this->getAuthor()), - "questiontext" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getQuestiontext(), 0)), - "obligatory" => array("text", $this->getObligatory()), - "complete" => array("text", $this->isComplete()), - "tstamp" => array("integer", time()) - ), array( - "question_id" => array("integer", $this->getId()) - )); - - $this->log->debug("UPDATE svy_question id=".$this->getId()." SET: title=".$this->getTitle()." ..."); - } - - return $affectedRows; - } - - /** - * save material to db - */ - public function saveMaterial() - { - $ilDB = $this->db; - - include_once "./Services/Link/classes/class.ilInternalLink.php"; - - $this->log->debug("DELETE: svy_material question_fi=".$this->getId()); - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_material WHERE question_fi = %s", - array('integer'), - array($this->getId()) - ); - ilInternalLink::_deleteAllLinksOfSource("sqst", $this->getId()); - - foreach ($this->material as $material) - { - $next_id = $ilDB->nextId('svy_material'); - - $this->log->debug("INSERT: svy_material question_fi=".$this->getId()); - - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_material " . - "(material_id, question_fi, internal_link, import_id, material_title, tstamp," . - "text_material, external_link, file_material, material_type) ". - "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", - array('integer','integer','text','text','text','integer','text','text','text','integer'), - array( - $next_id, $this->getId(), $material->internal_link, $material->import_id, - $material->title, time(), $material->text_material, $material->external_link, - $material->file_material, $material->type) - ); - if (preg_match("/il_(\d*?)_(\w+)_(\d+)/", $material->internal_link, $matches)) - { - ilInternalLink::_saveLink("sqst", $this->getId(), $matches[2], $matches[3], $matches[1]); - } - } - } - - /** - * Creates a new question with a 0 timestamp when a new question is created - * This assures that an ID is given to the question if a file upload or something else occurs - * - * @return integer ID of the new question - */ - public function createNewQuestion() - { - $ilDB = $this->db; - - $obj_id = $this->getObjId(); - if ($obj_id > 0) - { - $next_id = $ilDB->nextId('svy_question'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_question (question_id, questiontype_fi, " . - "obj_fi, owner_fi, title, description, author, questiontext, obligatory, complete, " . - "created, original_id, tstamp) VALUES " . - "(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", - array('integer', 'integer', 'integer', 'integer', 'text', 'text', 'text', 'text', - 'text', 'text', 'integer', 'integer', 'integer'), - array( - $next_id, - $this->getQuestionTypeID(), - $obj_id, - $this->getOwner(), - NULL, - NULL, - $this->getAuthor(), - NULL, - "1", - "0", - time(), - NULL, - 0 - ) - ); - $this->log->debug("INSERT INTO svy_question question_id= ".$next_id." questiontype_fi= ".$this->getQuestionTypeID()); - - $this->setId($next_id); - } - return $this->getId(); - } - - /** - * Saves the learners input of the question to the database - * - * @access public - * @see $answers - */ - function saveWorkingData($limit_to = LIMIT_NO_LIMIT) - { - } - - /** - * Returns the image path for web accessable images of a question. - * The image path is under the CLIENT_WEB_DIR in assessment/REFERENCE_ID_OF_QUESTION_POOL/ID_OF_QUESTION/images - * - * @access public - */ - function getImagePath() - { - return CLIENT_WEB_DIR . "/survey/$this->obj_id/$this->id/images/"; - } - - /** - * Returns the materials path for web accessable materials of a question. - * The materials path is under the CLIENT_WEB_DIR in assessment/REFERENCE_ID_OF_QUESTION_POOL/ID_OF_QUESTION/materials - * - * @access public - */ - function getMaterialsPath() - { - return CLIENT_WEB_DIR . "/survey/$this->obj_id/$this->id/materials/"; - } - - /** - * Returns the web image path for web accessable images of a question. - * The image path is under the web accessable data dir in assessment/REFERENCE_ID_OF_QUESTION_POOL/ID_OF_QUESTION/images - * - * @access public - */ - function getImagePathWeb() - { - $webdir = ilUtil::removeTrailingPathSeparators(CLIENT_WEB_DIR) . "/survey/$this->obj_id/$this->id/images/"; - return str_replace(ilUtil::removeTrailingPathSeparators(ILIAS_ABSOLUTE_PATH), ilUtil::removeTrailingPathSeparators(ILIAS_HTTP_PATH), $webdir); - } - - /** - * Returns the web image path for web accessable images of a question. - * The image path is under the web accessable data dir in assessment/REFERENCE_ID_OF_QUESTION_POOL/ID_OF_QUESTION/images - * - * @access public - */ - function getMaterialsPathWeb() - { - $webdir = ilUtil::removeTrailingPathSeparators(CLIENT_WEB_DIR) . "/survey/$this->obj_id/$this->id/materials/"; - return str_replace(ilUtil::removeTrailingPathSeparators(ILIAS_ABSOLUTE_PATH), ilUtil::removeTrailingPathSeparators(ILIAS_HTTP_PATH), $webdir); - } - - /** - * Saves a category to the database - * - * @param string $categorytext The description of the category - * @result integer The database id of the category - * @access public - * @see $categories - */ - function saveCategoryToDb($categorytext, $neutral = 0) - { - $ilUser = $this->user; - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT title, category_id FROM svy_category WHERE title = %s AND neutral = %s AND owner_fi = %s", - array('text','text','integer'), - array($categorytext, $neutral, $ilUser->getId()) - ); - $insert = FALSE; - $returnvalue = ""; - if ($result->numRows()) - { - $insert = TRUE; - while ($row = $ilDB->fetchAssoc($result)) - { - if (strcmp($row["title"], $categorytext) == 0) - { - $returnvalue = $row["category_id"]; - $insert = FALSE; - } - } - } - else - { - $insert = TRUE; - } - if ($insert) - { - $next_id = $ilDB->nextId('svy_category'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_category (category_id, title, neutral, owner_fi, tstamp) VALUES (%s, %s, %s, %s, %s)", - array('integer','text','text','integer','integer'), - array($next_id, $categorytext, $neutral, $ilUser->getId(), time()) - ); - - $this->log->debug("INSERT INTO svy_category id=".$next_id); - - $returnvalue = $next_id; - } - return $returnvalue; - } - - /** - * Deletes datasets from the additional question table in the database - * - * @param integer $question_id The question id which should be deleted in the additional question table - * @access public - */ - function deleteAdditionalTableData($question_id) - { - $ilDB = $this->db; - - $this->log->debug("DELETE FROM ".$this->getAdditionalTableName()); - - $affectedRows = $ilDB->manipulateF("DELETE FROM " . $this->getAdditionalTableName() . " WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - } - - /** - * Deletes a question and all materials from the database - * - * @param integer $question_id The database id of the question - * @access private - */ - function delete($question_id) - { - $ilDB = $this->db; - - if ($question_id < 1) return; - - $result = $ilDB->queryF("SELECT obj_fi FROM svy_question WHERE question_id = %s", - array('integer'), - array($question_id) - ); - if ($result->numRows() == 1) - { - $row = $ilDB->fetchAssoc($result); - $obj_id = $row["obj_fi"]; - } - else - { - return; - } - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_answer WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_constraint WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - - $result = $ilDB->queryF("SELECT constraint_fi FROM svy_qst_constraint WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - while ($row = $ilDB->fetchObject($result)) - { - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_constraint WHERE constraint_id = %s", - array('integer'), - array($row->constraint_fi) - ); - } - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qst_constraint WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_qblk_qst WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_svy_qst WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_variable WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_question WHERE question_id = %s", - array('integer'), - array($question_id) - ); - - $this->deleteAdditionalTableData($question_id); - - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_material WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - - $this->log->debug("SET OF DELETES svy_answer, svy_constraint, svy_qst_constraint, svy_qblk_qst, svy_qst_oblig, svy_svy_qst, svy_variable, svy_question, svy_material WHERE question_fi = ".$question_id); - - include_once "./Services/Link/classes/class.ilInternalLink.php"; - ilInternalLink::_deleteAllLinksOfSource("sqst", $question_id); - - $directory = CLIENT_WEB_DIR . "/survey/" . $obj_id . "/$question_id"; - if (preg_match("/\d+/", $obj_id) and preg_match("/\d+/", $question_id) and is_dir($directory)) - { - ilUtil::delDir($directory); - } - - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - $mobs = ilObjMediaObject::_getMobsOfObject("spl:html", $question_id); - // remaining usages are not in text anymore -> delete them - // and media objects (note: delete method of ilObjMediaObject - // checks whether object is used in another context; if yes, - // the object is not deleted!) - foreach($mobs as $mob) - { - ilObjMediaObject::_removeUsage($mob, "spl:html", $question_id); - $mob_obj = new ilObjMediaObject($mob); - $mob_obj->delete(); - } - - include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); - ilSurveySkill::handleQuestionDeletion($question_id, $obj_id); - - $this->log->debug("UPDATE svy_question"); - - // #12772 - untie question copies from pool question - $ilDB->manipulate("UPDATE svy_question". - " SET original_id = NULL". - " WHERE original_id = ".$ilDB->quote($question_id, "integer")); - } - - /** - * Returns the question type of a question with a given id - * - * @param integer $question_id The database id of the question - * @result string The question type string - * @access private - */ - static function _getQuestionType($question_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - if ($question_id < 1) return ""; - - $result = $ilDB->queryF("SELECT type_tag FROM svy_question, svy_qtype WHERE svy_question.question_id = %s AND svy_question.questiontype_fi = svy_qtype.questiontype_id", - array('integer'), - array($question_id) - ); - if ($result->numRows() == 1) - { - $data = $ilDB->fetchAssoc($result); - return $data["type_tag"]; - } - else - { - return ""; - } - } - - /** - * Returns the question title of a question with a given id - * - * @param integer $question_id The database id of the question - * @result string The question title - * @access private - */ - static function _getTitle($question_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - if ($question_id < 1) return ""; - - $result = $ilDB->queryF("SELECT title FROM svy_question WHERE svy_question.question_id = %s", - array('integer'), - array($question_id) - ); - if ($result->numRows() == 1) - { - $data = $ilDB->fetchAssoc($result); - return $data["title"]; - } - else - { - return ""; - } - } - - /** - * Returns the original id of a question - * - * @param integer $question_id The database id of the question - * @return integer The database id of the original question - * @access public - */ - static function _getOriginalId($question_id, $a_return_question_id_if_no_original = true) - { - global $DIC; - - $ilDB = $DIC->database(); - $result = $ilDB->queryF("SELECT * FROM svy_question WHERE question_id = %s", - array('integer'), - array($question_id) - ); - if ($result->numRows() > 0) - { - $row = $ilDB->fetchAssoc($result); - if ($row["original_id"] > 0) - { - return $row["original_id"]; - } - else if((bool)$a_return_question_id_if_no_original) // #12419 - { - return $row["question_id"]; - } - } - else - { - return ""; - } - } - - function syncWithOriginal() - { - $ilDB = $this->db; - - if ($this->getOriginalId()) - { - $id = $this->getId(); - $original = $this->getOriginalId(); - - $this->setId($this->getOriginalId()); - $this->setOriginalId(NULL); - $this->saveToDb(); - - $this->setId($id); - $this->setOriginalId($original); - - $this->log->debug("DELETE FROM svy_material WHERE question_fi = ".$this->getOriginalId()); - - include_once "./Services/Link/classes/class.ilInternalLink.php"; - $affectedRows = $ilDB->manipulateF("DELETE FROM svy_material WHERE question_fi = %s", - array('integer'), - array($this->getOriginalId()) - ); - ilInternalLink::_deleteAllLinksOfSource("sqst", $this->original_id); - if (strlen($this->material["internal_link"])) - { - $next_id = $ilDB->nextId('svy_material'); - $affectedRows = $ilDB->manipulateF("INSERT INTO svy_material (material_id, question_fi, internal_link, import_id, material_title, tstamp) VALUES (%s, %s, %s, %s, %s, %s)", - array('integer', 'integer', 'text', 'text', 'text', 'integer'), - array($next_id, $this->getOriginalId(), $this->material["internal_link"], $this->material["import_id"], $this->material["title"], time()) - ); - - $this->log->debug("INSERT svy_material material_id=".$next_id." question_fi=".$this->getOriginalId()); - - if (preg_match("/il_(\d*?)_(\w+)_(\d+)/", $this->material["internal_link"], $matches)) - { - ilInternalLink::_saveLink("sqst", $this->getOriginalId(), $matches[2], $matches[3], $matches[1]); - } - } - } - } - - /** - * Returns a phrase for a given database id - * - * @result String The title of the phrase - * @access public - */ - function getPhrase($phrase_id) - { - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT title FROM svy_phrase WHERE phrase_id = %s", - array('integer'), - array($phrase_id) - ); - if ($row = $ilDB->fetchAssoc($result)) - { - return $row["title"]; - } - return ""; - } - - /** - * Returns true if the phrase title already exists for the current user - * - * @param string $title The title of the phrase - * @result boolean True, if the title exists, otherwise False - * @access public - */ - function phraseExists($title) - { - $ilUser = $this->user; - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT phrase_id FROM svy_phrase WHERE title = %s AND owner_fi = %s", - array('text', 'integer'), - array($title, $ilUser->getId()) - ); - return ($result->numRows() == 0) ? false : true; - } - - /** - * Returns true if the question already exists in the database - * - * @param integer $question_id The database id of the question - * @result boolean True, if the question exists, otherwise False - * @access public - */ - static function _questionExists($question_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - if ($question_id < 1) - { - return false; - } - - $result = $ilDB->queryF("SELECT question_id FROM svy_question WHERE question_id = %s", - array('integer'), - array($question_id) - ); - return ($result->numRows() == 1) ? true : false; - } - - function addInternalLink($material_id, $title = "") - { - if (strlen($material_id)) - { - if (strcmp($material_title, "") == 0) - { - if (preg_match("/il__(\w+)_(\d+)/", $material_id, $matches)) - { - $type = $matches[1]; - $target_id = $matches[2]; - $material_title = $this->lng->txt("obj_$type") . ": "; - switch ($type) - { - case "lm": - include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); - $cont_obj_gui = new ilObjContentObjectGUI("", $target_id, true); - $cont_obj = $cont_obj_gui->object; - $material_title .= $cont_obj->getTitle(); - break; - case "pg": - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $lm_id = ilLMObject::_lookupContObjID($target_id); - include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); - $cont_obj_gui = new ilObjContentObjectGUI("", $lm_id, FALSE); - $cont_obj = $cont_obj_gui->object; - $pg_obj = new ilLMPageObject($cont_obj, $target_id); - $material_title .= $pg_obj->getTitle(); - break; - case "st": - include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $lm_id = ilLMObject::_lookupContObjID($target_id); - include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); - $cont_obj_gui = new ilObjContentObjectGUI("", $lm_id, FALSE); - $cont_obj = $cont_obj_gui->object; - $st_obj = new ilStructureObject($cont_obj, $target_id); - $material_title .= $st_obj->getTitle(); - break; - case "git": - include_once "./Modules/Glossary/classes/class.ilGlossaryTerm.php"; - $material_title = $this->lng->txt("glossary_term") . ": " . ilGlossaryTerm::_lookGlossaryTerm($target_id); - break; - case "mob": - break; - } - } - } - include_once "./Modules/SurveyQuestionPool/classes/class.ilSurveyMaterial.php"; - $mat = new ilSurveyMaterial(); - $mat->type = 0; - $mat->internal_link = $material_id; - $mat->title = $material_title; - $this->addMaterial($mat); - $this->saveMaterial(); - } - } - - /** - * Deletes materials - * - * @param array $a_array Array with indexes of the materials to delete - */ - public function deleteMaterials($a_array) - { - foreach ($a_array as $idx) - { - unset($this->material[$idx]); - } - $this->material = array_values($this->material); - $this->saveMaterial(); - } - - /** - * Duplicates the materials of a question - * - * @param integer $question_id The database id of the original survey question - * @access public - */ - function duplicateMaterials($question_id) - { - foreach ($this->materials as $filename) - { - $materialspath = $this->getMaterialsPath(); - $materialspath_original = preg_replace("/([^\d])$this->id([^\d])/", "\${1}$question_id\${2}", $materialspath); - if (!file_exists($materialspath)) - { - ilUtil::makeDirParents($materialspath); - } - if (!copy($materialspath_original . $filename, $materialspath . $filename)) - { - print "material could not be duplicated!!!! "; - } - } - } - - public function addMaterial($obj_material) - { - array_push($this->material, $obj_material); - } - - /** - * Sets a material link for the question - * - * @param string $material_id An internal link pointing to the material - * @param boolean $is_import A boolean indication that the internal link was imported from another ILIAS installation - * @access public - */ - function setMaterial($material_id = "", $is_import = false, $material_title = "") - { - if (strcmp($material_id, "") != 0) - { - $import_id = ""; - if ($is_import) - { - $import_id = $material_id; - $material_id = self::_resolveInternalLink($import_id); - } - if (strcmp($material_title, "") == 0) - { - if (preg_match("/il__(\w+)_(\d+)/", $material_id, $matches)) - { - $type = $matches[1]; - $target_id = $matches[2]; - $material_title = $this->lng->txt("obj_$type") . ": "; - switch ($type) - { - case "lm": - include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); - $cont_obj_gui = new ilObjContentObjectGUI("", $target_id, true); - $cont_obj = $cont_obj_gui->object; - $material_title .= $cont_obj->getTitle(); - break; - case "pg": - include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $lm_id = ilLMObject::_lookupContObjID($target_id); - include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); - $cont_obj_gui = new ilObjContentObjectGUI("", $lm_id, FALSE); - $cont_obj = $cont_obj_gui->object; - $pg_obj = new ilLMPageObject($cont_obj, $target_id); - $material_title .= $pg_obj->getTitle(); - break; - case "st": - include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); - include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); - $lm_id = ilLMObject::_lookupContObjID($target_id); - include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); - $cont_obj_gui = new ilObjContentObjectGUI("", $lm_id, FALSE); - $cont_obj = $cont_obj_gui->object; - $st_obj = new ilStructureObject($cont_obj, $target_id); - $material_title .= $st_obj->getTitle(); - break; - case "git": - include_once "./Modules/Glossary/classes/class.ilGlossaryTerm.php"; - $material_title = $this->lng->txt("glossary_term") . ": " . ilGlossaryTerm::_lookGlossaryTerm($target_id); - break; - case "mob": - break; - } - } - } - $this->material = array( - "internal_link" => $material_id, - "import_id" => $import_id, - "title" => $material_title - ); - } - $this->saveMaterial(); - } - - static function _resolveInternalLink($internal_link) - { - if (preg_match("/il_(\d+)_(\w+)_(\d+)/", $internal_link, $matches)) - { - include_once "./Services/Link/classes/class.ilInternalLink.php"; - include_once "./Modules/LearningModule/classes/class.ilLMObject.php"; - include_once "./Modules/Glossary/classes/class.ilGlossaryTerm.php"; - switch ($matches[2]) - { - case "lm": - $resolved_link = ilLMObject::_getIdForImportId($internal_link); - break; - case "pg": - $resolved_link = ilInternalLink::_getIdForImportId("PageObject", $internal_link); - break; - case "st": - $resolved_link = ilInternalLink::_getIdForImportId("StructureObject", $internal_link); - break; - case "git": - $resolved_link = ilInternalLink::_getIdForImportId("GlossaryItem", $internal_link); - break; - case "mob": - $resolved_link = ilInternalLink::_getIdForImportId("MediaObject", $internal_link); - break; - } - if (strcmp($resolved_link, "") == 0) - { - $resolved_link = $internal_link; - } - } - else - { - $resolved_link = $internal_link; - } - return $resolved_link; - } - - static function _resolveIntLinks($question_id) - { - global $DIC; - - $ilDB = $DIC->database(); - $resolvedlinks = 0; - $result = $ilDB->queryF("SELECT * FROM svy_material WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - if ($result->numRows()) - { - while ($row = $ilDB->fetchAssoc($result)) - { - $internal_link = $row["internal_link"]; - include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; - $resolved_link = self::_resolveInternalLink($internal_link); - if (strcmp($internal_link, $resolved_link) != 0) - { - // internal link was resolved successfully - $affectedRows = $ilDB->manipulateF("UPDATE svy_material SET internal_link = %s, tstamp = %s WHERE material_id = %s", - array('text', 'integer', 'integer'), - array($resolved_link, time(), $row["material_id"]) - ); - $resolvedlinks++; - } - } - } - if ($resolvedlinks) - { - // there are resolved links -> reenter theses links to the database - - // delete all internal links from the database - include_once "./Services/Link/classes/class.ilInternalLink.php"; - ilInternalLink::_deleteAllLinksOfSource("sqst", $question_id); - - $result = $ilDB->queryF("SELECT * FROM svy_material WHERE question_fi = %s", - array('integer'), - array($question_id) - ); - if ($result->numRows()) - { - while ($row = $ilDB->fetchAssoc($result)) - { - if (preg_match("/il_(\d*?)_(\w+)_(\d+)/", $row["internal_link"], $matches)) - { - ilInternalLink::_saveLink("sqst", $question_id, $matches[2], $matches[3], $matches[1]); - } - } - } - } - } - - static function _getInternalLinkHref($target = "", $a_parent_ref_id = null) - { - global $DIC; - - $ilDB = $DIC->database(); - $linktypes = array( - "lm" => "LearningModule", - "pg" => "PageObject", - "st" => "StructureObject", - "git" => "GlossaryItem", - "mob" => "MediaObject" - ); - $href = ""; - if (preg_match("/il__(\w+)_(\d+)/", $target, $matches)) - { - $type = $matches[1]; - $target_id = $matches[2]; - switch($linktypes[$matches[1]]) - { - case "LearningModule": - $href = ilUtil::removeTrailingPathSeparators(ILIAS_HTTP_PATH) ."/goto.php?target=" . $type . "_" . $target_id; - break; - case "PageObject": - case "StructureObject": - $href = ilUtil::removeTrailingPathSeparators(ILIAS_HTTP_PATH) ."/goto.php?target=" . $type . "_" . $target_id; - break; - case "GlossaryItem": - $href = ilUtil::removeTrailingPathSeparators(ILIAS_HTTP_PATH) ."/goto.php?target=" . $type . "_" . $target_id; - break; - case "MediaObject": - $href = ilUtil::removeTrailingPathSeparators(ILIAS_HTTP_PATH) . "/ilias.php?baseClass=ilLMPresentationGUI&obj_type=" . $linktypes[$type] . "&cmd=media&ref_id=".$a_parent_ref_id."&mob_id=".$target_id; - break; - } - } - return $href; - } - - /** - * Returns true if the question is writeable by a certain user - * - * @param integer $question_id The database id of the question - * @param integer $user_id The database id of the user - * @result boolean True, if the question exists, otherwise False - * @access public - */ - static function _isWriteable($question_id, $user_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - if (($question_id < 1) || ($user_id < 1)) - { - return false; - } - - $result = $ilDB->queryF("SELECT obj_fi FROM svy_question WHERE question_id = %s", - array('integer'), - array($question_id) - ); - if ($result->numRows() == 1) - { - $row = $ilDB->fetchAssoc($result); - $qpl_object_id = $row["obj_fi"]; - include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; - return ilObjSurveyQuestionPool::_isWriteable($qpl_object_id, $user_id); - } - else - { - return false; - } - } - - /** - * Returns the question type ID of the question - * - * @return integer The question type of the question - * @access public - */ - function getQuestionTypeID() - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT questiontype_id FROM svy_qtype WHERE type_tag = %s", - array('text'), - array($this->getQuestionType()) - ); - if ($result->numRows() == 1) - { - $row = $ilDB->fetchAssoc($result); - return $row["questiontype_id"]; - } - else - { - return 0; - } - } - - /** - * Returns the question type of the question - * - * @return integer The question type of the question - * @access public - */ - function getQuestionType() - { - return ""; - } - - /** - * Include the php class file for a given question type - * - * @param string $question_type The type tag of the question type - * @return integer 0 if the class should be included, 1 if the GUI class should be included - * @access public - */ - static function _includeClass($question_type, $gui = 0) - { - $type = $question_type; - if ($gui == 1) $type .= "GUI"; - else if ($gui == 2) $type .= "Evaluation"; - if (file_exists("./Modules/SurveyQuestionPool/classes/class.".$type.".php")) - { - include_once "./Modules/SurveyQuestionPool/classes/class.".$type.".php"; - return true; - } - else - { - global $DIC; - - $ilPluginAdmin = $DIC["ilPluginAdmin"]; - $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_MODULE, "SurveyQuestionPool", "svyq"); - foreach ($pl_names as $pl_name) - { - $pl = ilPlugin::getPluginObject(IL_COMP_MODULE, "SurveyQuestionPool", "svyq", $pl_name); - if (strcmp($pl->getQuestionType(), $question_type) == 0) - { - $pl->includeClass("class.".$type.".php"); - return true; - } - } - } - return false; - } - - /** - * Return the translation for a given question type tag - * - * @param string $type_tag The type tag of the question type - * @access public - */ - static function _getQuestionTypeName($type_tag) - { - if (file_exists("./Modules/SurveyQuestionPool/classes/class.".$type_tag.".php")) - { - global $DIC; - - $lng = $DIC->language(); - return $lng->txt($type_tag); - } - else - { - global $DIC; - - $ilPluginAdmin = $DIC["ilPluginAdmin"]; - $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_MODULE, "SurveyQuestionPool", "svyq"); - foreach ($pl_names as $pl_name) - { - $pl = ilPlugin::getPluginObject(IL_COMP_MODULE, "SurveyQuestionPool", "svyq", $pl_name); - if (strcmp($pl->getQuestionType(), $type_tag) == 0) - { - return $pl->getQuestionTypeTranslation(); - } - } - } - return ""; - } - - - /** - * Creates an instance of a question with a given question id - * - * @param integer $question_id The question id - * @return object The question instance - * @access public - */ - static function _instanciateQuestion($question_id) - { - $question_type = self::_getQuestionType($question_id); - if($question_type) - { - self::_includeClass($question_type); - $question = new $question_type(); - $question->loadFromDb($question_id); - return $question; - } - } - - /** - * Creates an instance of a question GUI with a given question id - * - * @param integer $question_id The question id - * @return object The question GUI instance - * @access public - */ - static function _instanciateQuestionGUI($question_id) - { - $question_type = self::_getQuestionType($question_id); - if($question_type) - { - self::_includeClass($question_type, 1); - $guitype = $question_type . "GUI"; - $question = new $guitype($question_id); - return $question; - } - } - - /** - * Creates an instance of a question evaluation with a given question id - * - * @param integer $question_id The question id - * @return object The question evaluation instance - * @access public - */ - static function _instanciateQuestionEvaluation($question_id, array $a_finished_ids = null) - { - $question = self::_instanciateQuestion($question_id); - if($question) - { - $question_type = self::_getQuestionType($question_id); - self::_includeClass($question_type, 2); - $class = $question_type . "Evaluation"; - $ev = new $class($question, $a_finished_ids); - return $ev; - } - } - - /** - * Checks if a given string contains HTML or not - * - * @param string $a_text Text which should be checked - * - * @return boolean - * @access public - */ - function isHTML($a_text) - { - if (preg_match("/<[^>]*?>/", $a_text)) - { - return TRUE; - } - else - { - return FALSE; - } - } - - /** - * Reads an QTI material tag an creates a text string - * - * @param string $a_material QTI material tag - * @return string text or xhtml string - * @access public - */ - function QTIMaterialToString($a_material) - { - $svy_log = ilLoggerFactory::getLogger("svy"); - $svy_log->debug("material count: ".$a_material->getMaterialCount()); - - $result = ""; - for ($i = 0; $i < $a_material->getMaterialCount(); $i++) - { - $material = $a_material->getMaterial($i); - if (strcmp($material["type"], "mattext") == 0) - { - $result .= $material["material"]->getContent(); - } - if (strcmp($material["type"], "matimage") == 0) - { - $matimage = $material["material"]; - if (preg_match("/(il_([0-9]+)_mob_([0-9]+))/", $matimage->getLabel(), $matches)) - { - // import an mediaobject which was inserted using tiny mce - if (!is_array($_SESSION["import_mob_xhtml"])) $_SESSION["import_mob_xhtml"] = array(); - array_push($_SESSION["import_mob_xhtml"], array("mob" => $matimage->getLabel(), "uri" => $matimage->getUri())); - } - } - } - return $result; - } - - /** - * Creates an XML material tag from a plain text or xhtml text - * - * @param object $a_xml_writer Reference to the ILIAS XML writer - * @param string $a_material plain text or html text containing the material - * @return string XML material tag - * @access public - */ - function addMaterialTag(&$a_xml_writer, $a_material, $close_material_tag = TRUE, $add_mobs = TRUE, $a_attrs = null) - { - include_once "./Services/RTE/classes/class.ilRTE.php"; - include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); - - $a_xml_writer->xmlStartTag("material"); - $attrs = array( - "type" => "text/plain" - ); - if ($this->isHTML($a_material)) - { - $attrs["type"] = "text/xhtml"; - } - if (is_array($a_attrs)) - { - $attrs = array_merge($attrs, $a_attrs); - } - $a_xml_writer->xmlElement("mattext", $attrs, ilRTE::_replaceMediaObjectImageSrc($a_material, 0)); - - if ($add_mobs) - { - $mobs = ilObjMediaObject::_getMobsOfObject("spl:html", $this->getId()); - foreach ($mobs as $mob) - { - $mob_obj = new ilObjMediaObject($mob); - $imgattrs = array( - "label" => "il_" . IL_INST_ID . "_mob_" . $mob, - "uri" => "objects/" . "il_" . IL_INST_ID . "_mob_" . $mob . "/" . $mob_obj->getTitle(), - "type" => "spl:html", - "id" => $this->getId() - ); - $a_xml_writer->xmlElement("matimage", $imgattrs, NULL); - } - } - if ($close_material_tag) $a_xml_writer->xmlEndTag("material"); - } - - /** - * Prepares a string for a text area output in surveys - * - * @param string $txt_output String which should be prepared for output - * @access public - */ - function prepareTextareaOutput($txt_output, $prepare_for_latex_output = FALSE) - { - return ilUtil::prepareTextareaOutput($txt_output, $prepare_for_latex_output); - } - - /** - * Returns the question data fields from the database - * - * @param integer $id The question ID from the database - * @return array Array containing the question fields and data from the database - * @access public - */ - function getQuestionDataArray($id) - { - return array(); - } - - /** - * Creates the user data of the svy_answer table from the POST data - * - * @return array User data according to the svy_answer table - * @access public - */ - function &getWorkingDataFromUserInput($post_data) - { - // overwrite in inherited classes - $data = array(); - return $data; - } - - /** - * Import additional meta data from the question import file. Usually - * the meta data section is used to store question elements which are not - * part of the standard XML schema. - * - * @return array $a_meta Array containing the additional meta data - * @access public - */ - function importAdditionalMetadata($a_meta) - { - // overwrite in inherited classes - } - - /** - * Import response data from the question import file - * - * @return array $a_data Array containing the response data - * @access public - */ - function importResponses($a_data) - { - // overwrite in inherited classes - } - - /** - * Import bipolar adjectives from the question import file - * - * @return array $a_data Array containing the adjectives - * @access public - */ - function importAdjectives($a_data) - { - // overwrite in inherited classes - } - - /** - * Import matrix rows from the question import file - * - * @return array $a_data Array containing the matrix rows - * @access public - */ - function importMatrix($a_data) - { - // overwrite in inherited classes - } - - /** - * Returns if the question is usable for preconditions - * - * @return boolean TRUE if the question is usable for a precondition, FALSE otherwise - * @access public - */ - function usableForPrecondition() - { - // overwrite in inherited classes - return FALSE; - } - - /** - * Returns the available relations for the question - * - * @return array An array containing the available relations - * @access public - */ - function getAvailableRelations() - { - // overwrite in inherited classes - return array(); - } - - /** - * Returns the options for preconditions - * - * @return array - */ - public function getPreconditionOptions() - { - // overwrite in inherited classes - } - - /** - * Returns the output for a precondition value - * - * @param string $value The precondition value - * @return string The output of the precondition value - * @access public - */ - function getPreconditionValueOutput($value) - { - // overwrite in inherited classes - return $value; - } - - /** - * Creates a form property for the precondition value - * - * @return The ILIAS form element - * @access public - */ - public function getPreconditionSelectValue($default = "", $title, $variable) - { - // overwrite in inherited classes - return null; - } - - function setOriginalId($original_id) - { - $this->original_id = $original_id; - } - - function getOriginalId() - { - return $this->original_id; - } - - public function getMaterial() - { - return $this->material; - } - - public function setSubtype($a_subtype) - { - // do nothing - } - - public function getSubtype() - { - // do nothing - return null; - } - - /** - * Object getter - */ - public function __get($value) - { - switch ($value) - { - default: - if (array_key_exists($value, $this->arrData)) - { - return $this->arrData[$value]; - } - else - { - return null; - } - break; - } - } - - /** - * Object setter - */ - public function __set($key, $value) - { - switch ($key) - { - default: - $this->arrData[$key] = $value; - break; - } - } - - /** - * Change original id of existing question in db - * - * @param int $a_question_id - * @param int $a_original_id - * @param int $a_object_id - */ - public static function _changeOriginalId($a_question_id, $a_original_id, $a_object_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $ilDB->manipulate("UPDATE svy_question". - " SET original_id = ".$ilDB->quote($a_original_id, "integer").",". - " obj_fi = ".$ilDB->quote($a_object_id, "integer"). - " WHERE question_id = ".$ilDB->quote($a_question_id, "integer")); - } - - public function getCopyIds($a_group_by_survey = false) - { - $ilDB = $this->db; - - $set = $ilDB->query("SELECT q.question_id,s.obj_fi". - " FROM svy_question q". - " JOIN svy_svy_qst sq ON (sq.question_fi = q.question_id)". - " JOIN svy_svy s ON (s.survey_id = sq.survey_fi)". - " WHERE original_id = ".$ilDB->quote($this->getId(), "integer")); - $res = array(); - while($row = $ilDB->fetchAssoc($set)) - { - if(!$a_group_by_survey) - { - $res[] = $row["question_id"]; - } - else - { - $res[$row["obj_fi"]][] = $row["question_id"]; - } - } - return $res; - } - - public function hasCopies() - { - return (bool)sizeof($this->getCopyIds()); - } - - public static function _lookupSurveyObjId($a_question_id) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT svy_svy.obj_fi FROM svy_svy_qst". - " JOIN svy_svy ON (svy_svy.survey_id = svy_svy_qst.survey_fi)". - " WHERE svy_svy_qst.question_fi = ".$ilDB->quote($a_question_id, "integer")); - $row = $ilDB->fetchAssoc($set); - if($ilDB->numRows($set)) - { - return $row["obj_fi"]; - } - } - - /** - * Lookip obj fi - * - * @param - * @return - */ - static function lookupObjFi($a_qid) - { - global $DIC; - - $ilDB = $DIC->database(); - - $set = $ilDB->query("SELECT obj_fi FROM svy_question ". - " WHERE question_id = ".$ilDB->quote($a_qid, "integer") - ); - $rec = $ilDB->fetchAssoc($set); - return $rec["obj_fi"]; - } - - /** - * Strip slashes with add space fallback, see https://mantis.ilias.de/view.php?id=19727 - * and https://mantis.ilias.de/view.php?id=24200 - * - * @param string $a_str string - * @return string - */ - function stripSlashesAddSpaceFallback($a_str) - { - $str = ilUtil::stripSlashes($a_str); - if ($str != $a_str) - { - $str = ilUtil::stripSlashes(str_replace("<", "< ", $a_str)); - } - return $str; - } - - + $next_id = $ilDB->nextId('svy_question'); + $affectedRows = $ilDB->insert("svy_question", array( + "question_id" => array("integer", $next_id), + "questiontype_fi" => array("integer", $this->getQuestionTypeID()), + "obj_fi" => array("integer", $this->getObjId()), + "owner_fi" => array("integer", $this->getOwner()), + "title" => array("text", $this->getTitle()), + "label" => array("text", (strlen($this->label)) ? $this->label : null), + "description" => array("text", $this->getDescription()), + "author" => array("text", $this->getAuthor()), + "questiontext" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getQuestiontext(), 0)), + "obligatory" => array("text", $this->getObligatory()), + "complete" => array("text", $this->isComplete()), + "created" => array("integer", time()), + "original_id" => array("integer", ($original_id) ? $original_id : null), + "tstamp" => array("integer", time()) + )); + + //$this->log->debug("INSERT: svy_question id=".$next_id." questiontype_fi=".$this->getQuestionTypeID()." obj_fi".$this->getObjId()." title=".$this->getTitle()." ..."); + + $this->setId($next_id); + } else { + // update existing dataset + $affectedRows = $ilDB->update("svy_question", array( + "title" => array("text", $this->getTitle()), + "label" => array("text", (strlen($this->label)) ? $this->label : null), + "description" => array("text", $this->getDescription()), + "author" => array("text", $this->getAuthor()), + "questiontext" => array("clob", ilRTE::_replaceMediaObjectImageSrc($this->getQuestiontext(), 0)), + "obligatory" => array("text", $this->getObligatory()), + "complete" => array("text", $this->isComplete()), + "tstamp" => array("integer", time()) + ), array( + "question_id" => array("integer", $this->getId()) + )); + + $this->log->debug("UPDATE svy_question id=" . $this->getId() . " SET: title=" . $this->getTitle() . " ..."); + } + + return $affectedRows; + } + + /** + * save material to db + */ + public function saveMaterial() + { + $ilDB = $this->db; + + include_once "./Services/Link/classes/class.ilInternalLink.php"; + + $this->log->debug("DELETE: svy_material question_fi=" . $this->getId()); + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_material WHERE question_fi = %s", + array('integer'), + array($this->getId()) + ); + ilInternalLink::_deleteAllLinksOfSource("sqst", $this->getId()); + + foreach ($this->material as $material) { + $next_id = $ilDB->nextId('svy_material'); + + $this->log->debug("INSERT: svy_material question_fi=" . $this->getId()); + + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_material " . + "(material_id, question_fi, internal_link, import_id, material_title, tstamp," . + "text_material, external_link, file_material, material_type) " . + "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", + array('integer','integer','text','text','text','integer','text','text','text','integer'), + array( + $next_id, $this->getId(), $material->internal_link, $material->import_id, + $material->title, time(), $material->text_material, $material->external_link, + $material->file_material, $material->type) + ); + if (preg_match("/il_(\d*?)_(\w+)_(\d+)/", $material->internal_link, $matches)) { + ilInternalLink::_saveLink("sqst", $this->getId(), $matches[2], $matches[3], $matches[1]); + } + } + } + + /** + * Creates a new question with a 0 timestamp when a new question is created + * This assures that an ID is given to the question if a file upload or something else occurs + * + * @return integer ID of the new question + */ + public function createNewQuestion() + { + $ilDB = $this->db; + + $obj_id = $this->getObjId(); + if ($obj_id > 0) { + $next_id = $ilDB->nextId('svy_question'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_question (question_id, questiontype_fi, " . + "obj_fi, owner_fi, title, description, author, questiontext, obligatory, complete, " . + "created, original_id, tstamp) VALUES " . + "(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", + array('integer', 'integer', 'integer', 'integer', 'text', 'text', 'text', 'text', + 'text', 'text', 'integer', 'integer', 'integer'), + array( + $next_id, + $this->getQuestionTypeID(), + $obj_id, + $this->getOwner(), + null, + null, + $this->getAuthor(), + null, + "1", + "0", + time(), + null, + 0 + ) + ); + $this->log->debug("INSERT INTO svy_question question_id= " . $next_id . " questiontype_fi= " . $this->getQuestionTypeID()); + + $this->setId($next_id); + } + return $this->getId(); + } + + /** + * Saves the learners input of the question to the database + * + * @access public + * @see $answers + */ + public function saveWorkingData($limit_to = LIMIT_NO_LIMIT) + { + } + + /** + * Returns the image path for web accessable images of a question. + * The image path is under the CLIENT_WEB_DIR in assessment/REFERENCE_ID_OF_QUESTION_POOL/ID_OF_QUESTION/images + * + * @access public + */ + public function getImagePath() + { + return CLIENT_WEB_DIR . "/survey/$this->obj_id/$this->id/images/"; + } + + /** + * Returns the materials path for web accessable materials of a question. + * The materials path is under the CLIENT_WEB_DIR in assessment/REFERENCE_ID_OF_QUESTION_POOL/ID_OF_QUESTION/materials + * + * @access public + */ + public function getMaterialsPath() + { + return CLIENT_WEB_DIR . "/survey/$this->obj_id/$this->id/materials/"; + } + + /** + * Returns the web image path for web accessable images of a question. + * The image path is under the web accessable data dir in assessment/REFERENCE_ID_OF_QUESTION_POOL/ID_OF_QUESTION/images + * + * @access public + */ + public function getImagePathWeb() + { + $webdir = ilUtil::removeTrailingPathSeparators(CLIENT_WEB_DIR) . "/survey/$this->obj_id/$this->id/images/"; + return str_replace(ilUtil::removeTrailingPathSeparators(ILIAS_ABSOLUTE_PATH), ilUtil::removeTrailingPathSeparators(ILIAS_HTTP_PATH), $webdir); + } + + /** + * Returns the web image path for web accessable images of a question. + * The image path is under the web accessable data dir in assessment/REFERENCE_ID_OF_QUESTION_POOL/ID_OF_QUESTION/images + * + * @access public + */ + public function getMaterialsPathWeb() + { + $webdir = ilUtil::removeTrailingPathSeparators(CLIENT_WEB_DIR) . "/survey/$this->obj_id/$this->id/materials/"; + return str_replace(ilUtil::removeTrailingPathSeparators(ILIAS_ABSOLUTE_PATH), ilUtil::removeTrailingPathSeparators(ILIAS_HTTP_PATH), $webdir); + } + + /** + * Saves a category to the database + * + * @param string $categorytext The description of the category + * @result integer The database id of the category + * @access public + * @see $categories + */ + public function saveCategoryToDb($categorytext, $neutral = 0) + { + $ilUser = $this->user; + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT title, category_id FROM svy_category WHERE title = %s AND neutral = %s AND owner_fi = %s", + array('text','text','integer'), + array($categorytext, $neutral, $ilUser->getId()) + ); + $insert = false; + $returnvalue = ""; + if ($result->numRows()) { + $insert = true; + while ($row = $ilDB->fetchAssoc($result)) { + if (strcmp($row["title"], $categorytext) == 0) { + $returnvalue = $row["category_id"]; + $insert = false; + } + } + } else { + $insert = true; + } + if ($insert) { + $next_id = $ilDB->nextId('svy_category'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_category (category_id, title, neutral, owner_fi, tstamp) VALUES (%s, %s, %s, %s, %s)", + array('integer','text','text','integer','integer'), + array($next_id, $categorytext, $neutral, $ilUser->getId(), time()) + ); + + $this->log->debug("INSERT INTO svy_category id=" . $next_id); + + $returnvalue = $next_id; + } + return $returnvalue; + } + + /** + * Deletes datasets from the additional question table in the database + * + * @param integer $question_id The question id which should be deleted in the additional question table + * @access public + */ + public function deleteAdditionalTableData($question_id) + { + $ilDB = $this->db; + + $this->log->debug("DELETE FROM " . $this->getAdditionalTableName()); + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM " . $this->getAdditionalTableName() . " WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + } + + /** + * Deletes a question and all materials from the database + * + * @param integer $question_id The database id of the question + * @access private + */ + public function delete($question_id) + { + $ilDB = $this->db; + + if ($question_id < 1) { + return; + } + + $result = $ilDB->queryF( + "SELECT obj_fi FROM svy_question WHERE question_id = %s", + array('integer'), + array($question_id) + ); + if ($result->numRows() == 1) { + $row = $ilDB->fetchAssoc($result); + $obj_id = $row["obj_fi"]; + } else { + return; + } + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_answer WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_constraint WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + + $result = $ilDB->queryF( + "SELECT constraint_fi FROM svy_qst_constraint WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + while ($row = $ilDB->fetchObject($result)) { + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_constraint WHERE constraint_id = %s", + array('integer'), + array($row->constraint_fi) + ); + } + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_qst_constraint WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_qblk_qst WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_svy_qst WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_variable WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_question WHERE question_id = %s", + array('integer'), + array($question_id) + ); + + $this->deleteAdditionalTableData($question_id); + + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_material WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + + $this->log->debug("SET OF DELETES svy_answer, svy_constraint, svy_qst_constraint, svy_qblk_qst, svy_qst_oblig, svy_svy_qst, svy_variable, svy_question, svy_material WHERE question_fi = " . $question_id); + + include_once "./Services/Link/classes/class.ilInternalLink.php"; + ilInternalLink::_deleteAllLinksOfSource("sqst", $question_id); + + $directory = CLIENT_WEB_DIR . "/survey/" . $obj_id . "/$question_id"; + if (preg_match("/\d+/", $obj_id) and preg_match("/\d+/", $question_id) and is_dir($directory)) { + ilUtil::delDir($directory); + } + + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + $mobs = ilObjMediaObject::_getMobsOfObject("spl:html", $question_id); + // remaining usages are not in text anymore -> delete them + // and media objects (note: delete method of ilObjMediaObject + // checks whether object is used in another context; if yes, + // the object is not deleted!) + foreach ($mobs as $mob) { + ilObjMediaObject::_removeUsage($mob, "spl:html", $question_id); + $mob_obj = new ilObjMediaObject($mob); + $mob_obj->delete(); + } + + include_once("./Modules/Survey/classes/class.ilSurveySkill.php"); + ilSurveySkill::handleQuestionDeletion($question_id, $obj_id); + + $this->log->debug("UPDATE svy_question"); + + // #12772 - untie question copies from pool question + $ilDB->manipulate("UPDATE svy_question" . + " SET original_id = NULL" . + " WHERE original_id = " . $ilDB->quote($question_id, "integer")); + } + + /** + * Returns the question type of a question with a given id + * + * @param integer $question_id The database id of the question + * @result string The question type string + * @access private + */ + public static function _getQuestionType($question_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + if ($question_id < 1) { + return ""; + } + + $result = $ilDB->queryF( + "SELECT type_tag FROM svy_question, svy_qtype WHERE svy_question.question_id = %s AND svy_question.questiontype_fi = svy_qtype.questiontype_id", + array('integer'), + array($question_id) + ); + if ($result->numRows() == 1) { + $data = $ilDB->fetchAssoc($result); + return $data["type_tag"]; + } else { + return ""; + } + } + + /** + * Returns the question title of a question with a given id + * + * @param integer $question_id The database id of the question + * @result string The question title + * @access private + */ + public static function _getTitle($question_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + if ($question_id < 1) { + return ""; + } + + $result = $ilDB->queryF( + "SELECT title FROM svy_question WHERE svy_question.question_id = %s", + array('integer'), + array($question_id) + ); + if ($result->numRows() == 1) { + $data = $ilDB->fetchAssoc($result); + return $data["title"]; + } else { + return ""; + } + } + + /** + * Returns the original id of a question + * + * @param integer $question_id The database id of the question + * @return integer The database id of the original question + * @access public + */ + public static function _getOriginalId($question_id, $a_return_question_id_if_no_original = true) + { + global $DIC; + + $ilDB = $DIC->database(); + $result = $ilDB->queryF( + "SELECT * FROM svy_question WHERE question_id = %s", + array('integer'), + array($question_id) + ); + if ($result->numRows() > 0) { + $row = $ilDB->fetchAssoc($result); + if ($row["original_id"] > 0) { + return $row["original_id"]; + } elseif ((bool) $a_return_question_id_if_no_original) { // #12419 + return $row["question_id"]; + } + } else { + return ""; + } + } + + public function syncWithOriginal() + { + $ilDB = $this->db; + + if ($this->getOriginalId()) { + $id = $this->getId(); + $original = $this->getOriginalId(); + + $this->setId($this->getOriginalId()); + $this->setOriginalId(null); + $this->saveToDb(); + + $this->setId($id); + $this->setOriginalId($original); + + $this->log->debug("DELETE FROM svy_material WHERE question_fi = " . $this->getOriginalId()); + + include_once "./Services/Link/classes/class.ilInternalLink.php"; + $affectedRows = $ilDB->manipulateF( + "DELETE FROM svy_material WHERE question_fi = %s", + array('integer'), + array($this->getOriginalId()) + ); + ilInternalLink::_deleteAllLinksOfSource("sqst", $this->original_id); + if (strlen($this->material["internal_link"])) { + $next_id = $ilDB->nextId('svy_material'); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO svy_material (material_id, question_fi, internal_link, import_id, material_title, tstamp) VALUES (%s, %s, %s, %s, %s, %s)", + array('integer', 'integer', 'text', 'text', 'text', 'integer'), + array($next_id, $this->getOriginalId(), $this->material["internal_link"], $this->material["import_id"], $this->material["title"], time()) + ); + + $this->log->debug("INSERT svy_material material_id=" . $next_id . " question_fi=" . $this->getOriginalId()); + + if (preg_match("/il_(\d*?)_(\w+)_(\d+)/", $this->material["internal_link"], $matches)) { + ilInternalLink::_saveLink("sqst", $this->getOriginalId(), $matches[2], $matches[3], $matches[1]); + } + } + } + } + + /** + * Returns a phrase for a given database id + * + * @result String The title of the phrase + * @access public + */ + public function getPhrase($phrase_id) + { + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT title FROM svy_phrase WHERE phrase_id = %s", + array('integer'), + array($phrase_id) + ); + if ($row = $ilDB->fetchAssoc($result)) { + return $row["title"]; + } + return ""; + } + + /** + * Returns true if the phrase title already exists for the current user + * + * @param string $title The title of the phrase + * @result boolean True, if the title exists, otherwise False + * @access public + */ + public function phraseExists($title) + { + $ilUser = $this->user; + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT phrase_id FROM svy_phrase WHERE title = %s AND owner_fi = %s", + array('text', 'integer'), + array($title, $ilUser->getId()) + ); + return ($result->numRows() == 0) ? false : true; + } + + /** + * Returns true if the question already exists in the database + * + * @param integer $question_id The database id of the question + * @result boolean True, if the question exists, otherwise False + * @access public + */ + public static function _questionExists($question_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + if ($question_id < 1) { + return false; + } + + $result = $ilDB->queryF( + "SELECT question_id FROM svy_question WHERE question_id = %s", + array('integer'), + array($question_id) + ); + return ($result->numRows() == 1) ? true : false; + } + + public function addInternalLink($material_id, $title = "") + { + if (strlen($material_id)) { + if (strcmp($material_title, "") == 0) { + if (preg_match("/il__(\w+)_(\d+)/", $material_id, $matches)) { + $type = $matches[1]; + $target_id = $matches[2]; + $material_title = $this->lng->txt("obj_$type") . ": "; + switch ($type) { + case "lm": + include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); + $cont_obj_gui = new ilObjContentObjectGUI("", $target_id, true); + $cont_obj = $cont_obj_gui->object; + $material_title .= $cont_obj->getTitle(); + break; + case "pg": + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $lm_id = ilLMObject::_lookupContObjID($target_id); + include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); + $cont_obj_gui = new ilObjContentObjectGUI("", $lm_id, false); + $cont_obj = $cont_obj_gui->object; + $pg_obj = new ilLMPageObject($cont_obj, $target_id); + $material_title .= $pg_obj->getTitle(); + break; + case "st": + include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $lm_id = ilLMObject::_lookupContObjID($target_id); + include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); + $cont_obj_gui = new ilObjContentObjectGUI("", $lm_id, false); + $cont_obj = $cont_obj_gui->object; + $st_obj = new ilStructureObject($cont_obj, $target_id); + $material_title .= $st_obj->getTitle(); + break; + case "git": + include_once "./Modules/Glossary/classes/class.ilGlossaryTerm.php"; + $material_title = $this->lng->txt("glossary_term") . ": " . ilGlossaryTerm::_lookGlossaryTerm($target_id); + break; + case "mob": + break; + } + } + } + include_once "./Modules/SurveyQuestionPool/classes/class.ilSurveyMaterial.php"; + $mat = new ilSurveyMaterial(); + $mat->type = 0; + $mat->internal_link = $material_id; + $mat->title = $material_title; + $this->addMaterial($mat); + $this->saveMaterial(); + } + } + + /** + * Deletes materials + * + * @param array $a_array Array with indexes of the materials to delete + */ + public function deleteMaterials($a_array) + { + foreach ($a_array as $idx) { + unset($this->material[$idx]); + } + $this->material = array_values($this->material); + $this->saveMaterial(); + } + + /** + * Duplicates the materials of a question + * + * @param integer $question_id The database id of the original survey question + * @access public + */ + public function duplicateMaterials($question_id) + { + foreach ($this->materials as $filename) { + $materialspath = $this->getMaterialsPath(); + $materialspath_original = preg_replace("/([^\d])$this->id([^\d])/", "\${1}$question_id\${2}", $materialspath); + if (!file_exists($materialspath)) { + ilUtil::makeDirParents($materialspath); + } + if (!copy($materialspath_original . $filename, $materialspath . $filename)) { + print "material could not be duplicated!!!! "; + } + } + } + + public function addMaterial($obj_material) + { + array_push($this->material, $obj_material); + } + + /** + * Sets a material link for the question + * + * @param string $material_id An internal link pointing to the material + * @param boolean $is_import A boolean indication that the internal link was imported from another ILIAS installation + * @access public + */ + public function setMaterial($material_id = "", $is_import = false, $material_title = "") + { + if (strcmp($material_id, "") != 0) { + $import_id = ""; + if ($is_import) { + $import_id = $material_id; + $material_id = self::_resolveInternalLink($import_id); + } + if (strcmp($material_title, "") == 0) { + if (preg_match("/il__(\w+)_(\d+)/", $material_id, $matches)) { + $type = $matches[1]; + $target_id = $matches[2]; + $material_title = $this->lng->txt("obj_$type") . ": "; + switch ($type) { + case "lm": + include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); + $cont_obj_gui = new ilObjContentObjectGUI("", $target_id, true); + $cont_obj = $cont_obj_gui->object; + $material_title .= $cont_obj->getTitle(); + break; + case "pg": + include_once("./Modules/LearningModule/classes/class.ilLMPageObject.php"); + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $lm_id = ilLMObject::_lookupContObjID($target_id); + include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); + $cont_obj_gui = new ilObjContentObjectGUI("", $lm_id, false); + $cont_obj = $cont_obj_gui->object; + $pg_obj = new ilLMPageObject($cont_obj, $target_id); + $material_title .= $pg_obj->getTitle(); + break; + case "st": + include_once("./Modules/LearningModule/classes/class.ilStructureObject.php"); + include_once("./Modules/LearningModule/classes/class.ilLMObject.php"); + $lm_id = ilLMObject::_lookupContObjID($target_id); + include_once("./Modules/LearningModule/classes/class.ilObjContentObjectGUI.php"); + $cont_obj_gui = new ilObjContentObjectGUI("", $lm_id, false); + $cont_obj = $cont_obj_gui->object; + $st_obj = new ilStructureObject($cont_obj, $target_id); + $material_title .= $st_obj->getTitle(); + break; + case "git": + include_once "./Modules/Glossary/classes/class.ilGlossaryTerm.php"; + $material_title = $this->lng->txt("glossary_term") . ": " . ilGlossaryTerm::_lookGlossaryTerm($target_id); + break; + case "mob": + break; + } + } + } + $this->material = array( + "internal_link" => $material_id, + "import_id" => $import_id, + "title" => $material_title + ); + } + $this->saveMaterial(); + } + + public static function _resolveInternalLink($internal_link) + { + if (preg_match("/il_(\d+)_(\w+)_(\d+)/", $internal_link, $matches)) { + include_once "./Services/Link/classes/class.ilInternalLink.php"; + include_once "./Modules/LearningModule/classes/class.ilLMObject.php"; + include_once "./Modules/Glossary/classes/class.ilGlossaryTerm.php"; + switch ($matches[2]) { + case "lm": + $resolved_link = ilLMObject::_getIdForImportId($internal_link); + break; + case "pg": + $resolved_link = ilInternalLink::_getIdForImportId("PageObject", $internal_link); + break; + case "st": + $resolved_link = ilInternalLink::_getIdForImportId("StructureObject", $internal_link); + break; + case "git": + $resolved_link = ilInternalLink::_getIdForImportId("GlossaryItem", $internal_link); + break; + case "mob": + $resolved_link = ilInternalLink::_getIdForImportId("MediaObject", $internal_link); + break; + } + if (strcmp($resolved_link, "") == 0) { + $resolved_link = $internal_link; + } + } else { + $resolved_link = $internal_link; + } + return $resolved_link; + } + + public static function _resolveIntLinks($question_id) + { + global $DIC; + + $ilDB = $DIC->database(); + $resolvedlinks = 0; + $result = $ilDB->queryF( + "SELECT * FROM svy_material WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + if ($result->numRows()) { + while ($row = $ilDB->fetchAssoc($result)) { + $internal_link = $row["internal_link"]; + include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; + $resolved_link = self::_resolveInternalLink($internal_link); + if (strcmp($internal_link, $resolved_link) != 0) { + // internal link was resolved successfully + $affectedRows = $ilDB->manipulateF( + "UPDATE svy_material SET internal_link = %s, tstamp = %s WHERE material_id = %s", + array('text', 'integer', 'integer'), + array($resolved_link, time(), $row["material_id"]) + ); + $resolvedlinks++; + } + } + } + if ($resolvedlinks) { + // there are resolved links -> reenter theses links to the database + + // delete all internal links from the database + include_once "./Services/Link/classes/class.ilInternalLink.php"; + ilInternalLink::_deleteAllLinksOfSource("sqst", $question_id); + + $result = $ilDB->queryF( + "SELECT * FROM svy_material WHERE question_fi = %s", + array('integer'), + array($question_id) + ); + if ($result->numRows()) { + while ($row = $ilDB->fetchAssoc($result)) { + if (preg_match("/il_(\d*?)_(\w+)_(\d+)/", $row["internal_link"], $matches)) { + ilInternalLink::_saveLink("sqst", $question_id, $matches[2], $matches[3], $matches[1]); + } + } + } + } + } + + public static function _getInternalLinkHref($target = "", $a_parent_ref_id = null) + { + global $DIC; + + $ilDB = $DIC->database(); + $linktypes = array( + "lm" => "LearningModule", + "pg" => "PageObject", + "st" => "StructureObject", + "git" => "GlossaryItem", + "mob" => "MediaObject" + ); + $href = ""; + if (preg_match("/il__(\w+)_(\d+)/", $target, $matches)) { + $type = $matches[1]; + $target_id = $matches[2]; + switch ($linktypes[$matches[1]]) { + case "LearningModule": + $href = ilUtil::removeTrailingPathSeparators(ILIAS_HTTP_PATH) . "/goto.php?target=" . $type . "_" . $target_id; + break; + case "PageObject": + case "StructureObject": + $href = ilUtil::removeTrailingPathSeparators(ILIAS_HTTP_PATH) . "/goto.php?target=" . $type . "_" . $target_id; + break; + case "GlossaryItem": + $href = ilUtil::removeTrailingPathSeparators(ILIAS_HTTP_PATH) . "/goto.php?target=" . $type . "_" . $target_id; + break; + case "MediaObject": + $href = ilUtil::removeTrailingPathSeparators(ILIAS_HTTP_PATH) . "/ilias.php?baseClass=ilLMPresentationGUI&obj_type=" . $linktypes[$type] . "&cmd=media&ref_id=" . $a_parent_ref_id . "&mob_id=" . $target_id; + break; + } + } + return $href; + } + + /** + * Returns true if the question is writeable by a certain user + * + * @param integer $question_id The database id of the question + * @param integer $user_id The database id of the user + * @result boolean True, if the question exists, otherwise False + * @access public + */ + public static function _isWriteable($question_id, $user_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + if (($question_id < 1) || ($user_id < 1)) { + return false; + } + + $result = $ilDB->queryF( + "SELECT obj_fi FROM svy_question WHERE question_id = %s", + array('integer'), + array($question_id) + ); + if ($result->numRows() == 1) { + $row = $ilDB->fetchAssoc($result); + $qpl_object_id = $row["obj_fi"]; + include_once "./Modules/SurveyQuestionPool/classes/class.ilObjSurveyQuestionPool.php"; + return ilObjSurveyQuestionPool::_isWriteable($qpl_object_id, $user_id); + } else { + return false; + } + } + + /** + * Returns the question type ID of the question + * + * @return integer The question type of the question + * @access public + */ + public function getQuestionTypeID() + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT questiontype_id FROM svy_qtype WHERE type_tag = %s", + array('text'), + array($this->getQuestionType()) + ); + if ($result->numRows() == 1) { + $row = $ilDB->fetchAssoc($result); + return $row["questiontype_id"]; + } else { + return 0; + } + } + + /** + * Returns the question type of the question + * + * @return integer The question type of the question + * @access public + */ + public function getQuestionType() + { + return ""; + } + + /** + * Include the php class file for a given question type + * + * @param string $question_type The type tag of the question type + * @return integer 0 if the class should be included, 1 if the GUI class should be included + * @access public + */ + public static function _includeClass($question_type, $gui = 0) + { + $type = $question_type; + if ($gui == 1) { + $type .= "GUI"; + } elseif ($gui == 2) { + $type .= "Evaluation"; + } + if (file_exists("./Modules/SurveyQuestionPool/classes/class." . $type . ".php")) { + include_once "./Modules/SurveyQuestionPool/classes/class." . $type . ".php"; + return true; + } else { + global $DIC; + + $ilPluginAdmin = $DIC["ilPluginAdmin"]; + $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_MODULE, "SurveyQuestionPool", "svyq"); + foreach ($pl_names as $pl_name) { + $pl = ilPlugin::getPluginObject(IL_COMP_MODULE, "SurveyQuestionPool", "svyq", $pl_name); + if (strcmp($pl->getQuestionType(), $question_type) == 0) { + $pl->includeClass("class." . $type . ".php"); + return true; + } + } + } + return false; + } + + /** + * Return the translation for a given question type tag + * + * @param string $type_tag The type tag of the question type + * @access public + */ + public static function _getQuestionTypeName($type_tag) + { + if (file_exists("./Modules/SurveyQuestionPool/classes/class." . $type_tag . ".php")) { + global $DIC; + + $lng = $DIC->language(); + return $lng->txt($type_tag); + } else { + global $DIC; + + $ilPluginAdmin = $DIC["ilPluginAdmin"]; + $pl_names = $ilPluginAdmin->getActivePluginsForSlot(IL_COMP_MODULE, "SurveyQuestionPool", "svyq"); + foreach ($pl_names as $pl_name) { + $pl = ilPlugin::getPluginObject(IL_COMP_MODULE, "SurveyQuestionPool", "svyq", $pl_name); + if (strcmp($pl->getQuestionType(), $type_tag) == 0) { + return $pl->getQuestionTypeTranslation(); + } + } + } + return ""; + } + + + /** + * Creates an instance of a question with a given question id + * + * @param integer $question_id The question id + * @return object The question instance + * @access public + */ + public static function _instanciateQuestion($question_id) + { + $question_type = self::_getQuestionType($question_id); + if ($question_type) { + self::_includeClass($question_type); + $question = new $question_type(); + $question->loadFromDb($question_id); + return $question; + } + } + + /** + * Creates an instance of a question GUI with a given question id + * + * @param integer $question_id The question id + * @return object The question GUI instance + * @access public + */ + public static function _instanciateQuestionGUI($question_id) + { + $question_type = self::_getQuestionType($question_id); + if ($question_type) { + self::_includeClass($question_type, 1); + $guitype = $question_type . "GUI"; + $question = new $guitype($question_id); + return $question; + } + } + + /** + * Creates an instance of a question evaluation with a given question id + * + * @param integer $question_id The question id + * @return object The question evaluation instance + * @access public + */ + public static function _instanciateQuestionEvaluation($question_id, array $a_finished_ids = null) + { + $question = self::_instanciateQuestion($question_id); + if ($question) { + $question_type = self::_getQuestionType($question_id); + self::_includeClass($question_type, 2); + $class = $question_type . "Evaluation"; + $ev = new $class($question, $a_finished_ids); + return $ev; + } + } + + /** + * Checks if a given string contains HTML or not + * + * @param string $a_text Text which should be checked + * + * @return boolean + * @access public + */ + public function isHTML($a_text) + { + if (preg_match("/<[^>]*?>/", $a_text)) { + return true; + } else { + return false; + } + } + + /** + * Reads an QTI material tag an creates a text string + * + * @param string $a_material QTI material tag + * @return string text or xhtml string + * @access public + */ + public function QTIMaterialToString($a_material) + { + $svy_log = ilLoggerFactory::getLogger("svy"); + $svy_log->debug("material count: " . $a_material->getMaterialCount()); + + $result = ""; + for ($i = 0; $i < $a_material->getMaterialCount(); $i++) { + $material = $a_material->getMaterial($i); + if (strcmp($material["type"], "mattext") == 0) { + $result .= $material["material"]->getContent(); + } + if (strcmp($material["type"], "matimage") == 0) { + $matimage = $material["material"]; + if (preg_match("/(il_([0-9]+)_mob_([0-9]+))/", $matimage->getLabel(), $matches)) { + // import an mediaobject which was inserted using tiny mce + if (!is_array($_SESSION["import_mob_xhtml"])) { + $_SESSION["import_mob_xhtml"] = array(); + } + array_push($_SESSION["import_mob_xhtml"], array("mob" => $matimage->getLabel(), "uri" => $matimage->getUri())); + } + } + } + return $result; + } + + /** + * Creates an XML material tag from a plain text or xhtml text + * + * @param object $a_xml_writer Reference to the ILIAS XML writer + * @param string $a_material plain text or html text containing the material + * @return string XML material tag + * @access public + */ + public function addMaterialTag(&$a_xml_writer, $a_material, $close_material_tag = true, $add_mobs = true, $a_attrs = null) + { + include_once "./Services/RTE/classes/class.ilRTE.php"; + include_once("./Services/MediaObjects/classes/class.ilObjMediaObject.php"); + + $a_xml_writer->xmlStartTag("material"); + $attrs = array( + "type" => "text/plain" + ); + if ($this->isHTML($a_material)) { + $attrs["type"] = "text/xhtml"; + } + if (is_array($a_attrs)) { + $attrs = array_merge($attrs, $a_attrs); + } + $a_xml_writer->xmlElement("mattext", $attrs, ilRTE::_replaceMediaObjectImageSrc($a_material, 0)); + + if ($add_mobs) { + $mobs = ilObjMediaObject::_getMobsOfObject("spl:html", $this->getId()); + foreach ($mobs as $mob) { + $mob_obj = new ilObjMediaObject($mob); + $imgattrs = array( + "label" => "il_" . IL_INST_ID . "_mob_" . $mob, + "uri" => "objects/" . "il_" . IL_INST_ID . "_mob_" . $mob . "/" . $mob_obj->getTitle(), + "type" => "spl:html", + "id" => $this->getId() + ); + $a_xml_writer->xmlElement("matimage", $imgattrs, null); + } + } + if ($close_material_tag) { + $a_xml_writer->xmlEndTag("material"); + } + } + + /** + * Prepares a string for a text area output in surveys + * + * @param string $txt_output String which should be prepared for output + * @access public + */ + public function prepareTextareaOutput($txt_output, $prepare_for_latex_output = false) + { + return ilUtil::prepareTextareaOutput($txt_output, $prepare_for_latex_output); + } + + /** + * Returns the question data fields from the database + * + * @param integer $id The question ID from the database + * @return array Array containing the question fields and data from the database + * @access public + */ + public function getQuestionDataArray($id) + { + return array(); + } + + /** + * Creates the user data of the svy_answer table from the POST data + * + * @return array User data according to the svy_answer table + * @access public + */ + public function &getWorkingDataFromUserInput($post_data) + { + // overwrite in inherited classes + $data = array(); + return $data; + } + + /** + * Import additional meta data from the question import file. Usually + * the meta data section is used to store question elements which are not + * part of the standard XML schema. + * + * @return array $a_meta Array containing the additional meta data + * @access public + */ + public function importAdditionalMetadata($a_meta) + { + // overwrite in inherited classes + } + + /** + * Import response data from the question import file + * + * @return array $a_data Array containing the response data + * @access public + */ + public function importResponses($a_data) + { + // overwrite in inherited classes + } + + /** + * Import bipolar adjectives from the question import file + * + * @return array $a_data Array containing the adjectives + * @access public + */ + public function importAdjectives($a_data) + { + // overwrite in inherited classes + } + + /** + * Import matrix rows from the question import file + * + * @return array $a_data Array containing the matrix rows + * @access public + */ + public function importMatrix($a_data) + { + // overwrite in inherited classes + } + + /** + * Returns if the question is usable for preconditions + * + * @return boolean TRUE if the question is usable for a precondition, FALSE otherwise + * @access public + */ + public function usableForPrecondition() + { + // overwrite in inherited classes + return false; + } + + /** + * Returns the available relations for the question + * + * @return array An array containing the available relations + * @access public + */ + public function getAvailableRelations() + { + // overwrite in inherited classes + return array(); + } + + /** + * Returns the options for preconditions + * + * @return array + */ + public function getPreconditionOptions() + { + // overwrite in inherited classes + } + + /** + * Returns the output for a precondition value + * + * @param string $value The precondition value + * @return string The output of the precondition value + * @access public + */ + public function getPreconditionValueOutput($value) + { + // overwrite in inherited classes + return $value; + } + + /** + * Creates a form property for the precondition value + * + * @return The ILIAS form element + * @access public + */ + public function getPreconditionSelectValue($default = "", $title, $variable) + { + // overwrite in inherited classes + return null; + } + + public function setOriginalId($original_id) + { + $this->original_id = $original_id; + } + + public function getOriginalId() + { + return $this->original_id; + } + + public function getMaterial() + { + return $this->material; + } + + public function setSubtype($a_subtype) + { + // do nothing + } + + public function getSubtype() + { + // do nothing + return null; + } + + /** + * Object getter + */ + public function __get($value) + { + switch ($value) { + default: + if (array_key_exists($value, $this->arrData)) { + return $this->arrData[$value]; + } else { + return null; + } + break; + } + } + + /** + * Object setter + */ + public function __set($key, $value) + { + switch ($key) { + default: + $this->arrData[$key] = $value; + break; + } + } + + /** + * Change original id of existing question in db + * + * @param int $a_question_id + * @param int $a_original_id + * @param int $a_object_id + */ + public static function _changeOriginalId($a_question_id, $a_original_id, $a_object_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $ilDB->manipulate("UPDATE svy_question" . + " SET original_id = " . $ilDB->quote($a_original_id, "integer") . "," . + " obj_fi = " . $ilDB->quote($a_object_id, "integer") . + " WHERE question_id = " . $ilDB->quote($a_question_id, "integer")); + } + + public function getCopyIds($a_group_by_survey = false) + { + $ilDB = $this->db; + + $set = $ilDB->query("SELECT q.question_id,s.obj_fi" . + " FROM svy_question q" . + " JOIN svy_svy_qst sq ON (sq.question_fi = q.question_id)" . + " JOIN svy_svy s ON (s.survey_id = sq.survey_fi)" . + " WHERE original_id = " . $ilDB->quote($this->getId(), "integer")); + $res = array(); + while ($row = $ilDB->fetchAssoc($set)) { + if (!$a_group_by_survey) { + $res[] = $row["question_id"]; + } else { + $res[$row["obj_fi"]][] = $row["question_id"]; + } + } + return $res; + } + + public function hasCopies() + { + return (bool) sizeof($this->getCopyIds()); + } + + public static function _lookupSurveyObjId($a_question_id) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query("SELECT svy_svy.obj_fi FROM svy_svy_qst" . + " JOIN svy_svy ON (svy_svy.survey_id = svy_svy_qst.survey_fi)" . + " WHERE svy_svy_qst.question_fi = " . $ilDB->quote($a_question_id, "integer")); + $row = $ilDB->fetchAssoc($set); + if ($ilDB->numRows($set)) { + return $row["obj_fi"]; + } + } + + /** + * Lookip obj fi + * + * @param + * @return + */ + public static function lookupObjFi($a_qid) + { + global $DIC; + + $ilDB = $DIC->database(); + + $set = $ilDB->query( + "SELECT obj_fi FROM svy_question " . + " WHERE question_id = " . $ilDB->quote($a_qid, "integer") + ); + $rec = $ilDB->fetchAssoc($set); + return $rec["obj_fi"]; + } + + /** + * Strip slashes with add space fallback, see https://mantis.ilias.de/view.php?id=19727 + * and https://mantis.ilias.de/view.php?id=24200 + * + * @param string $a_str string + * @return string + */ + public function stripSlashesAddSpaceFallback($a_str) + { + $str = ilUtil::stripSlashes($a_str); + if ($str != $a_str) { + $str = ilUtil::stripSlashes(str_replace("<", "< ", $a_str)); + } + return $str; + } } -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyQuestionEvaluation.php b/Modules/SurveyQuestionPool/classes/class.SurveyQuestionEvaluation.php index c454b4952877fe83c27bef8cbd11d78d545d7318..0417619bc918dd1f319be47548377516a28ab1ea 100644 --- a/Modules/SurveyQuestionPool/classes/class.SurveyQuestionEvaluation.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyQuestionEvaluation.php @@ -4,585 +4,532 @@ include_once "Modules/Survey/classes/class.ilSurveyEvaluationResults.php"; /** - * Survey question evaluation + * Survey question evaluation * * @author Jörg Lützenkirchen"; - $html[] = ($col != "") ? $col : " "; - $html[] = " | "; - } - $html[] = "
---|
"; + $html[] = ($col != "") ? $col : " "; + $html[] = " | "; + } + $html[] = "
"; - $html[] = ($col != "") ? $col : " "; - $html[] = " | "; - } - $html[] = "
"; - $html[] = ($col != "") ? $col : " "; - $html[] = " | "; - } - $html[] = "
$error_message
"); - } - if ($show_questiontext) - { - $this->outQuestionText($template); - } - $template->parseCurrentBlock(); - return $template->get(); - } + $template->setCurrentBlock("comborow"); + $template->setVariable("TEXT_SC", $cat->title); + $template->setVariable("VALUE_SC", ($cat->scale) ? ($cat->scale - 1) : $i); + if (is_array($working_data)) { + if (strcmp($working_data[0]["value"], "") != 0) { + if ($working_data[0]["value"] == $cat->scale-1) { + $template->setVariable("SELECTED_SC", " selected=\"selected\""); + } + } + } + $template->parseCurrentBlock(); + } + $template->setCurrentBlock("combooutput"); + $template->setVariable("QUESTION_ID", $this->object->getId()); + $template->setVariable("SELECT_OPTION", $this->lng->txt("select_option")); + $template->setVariable("TEXT_SELECTION", $this->lng->txt("selection")); + $template->parseCurrentBlock(); + break; + } + if ($question_title) { + $template->setVariable("QUESTION_TITLE", $this->object->getTitle()); + } + $template->setCurrentBlock("question_data"); + if (strcmp($error_message, "") != 0) { + $template->setVariable("ERROR_MESSAGE", "$error_message
"); + } + if ($show_questiontext) { + $this->outQuestionText($template); + } + $template->parseCurrentBlock(); + return $template->get(); + } } - -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyTextQuestion.php b/Modules/SurveyQuestionPool/classes/class.SurveyTextQuestion.php index 775414c8488ad8c5f3be0be61dc89f654ca47f63..f4b9b46ccb0ac58c276f41b69933da74f36b2acc 100755 --- a/Modules/SurveyQuestionPool/classes/class.SurveyTextQuestion.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyTextQuestion.php @@ -34,441 +34,418 @@ include_once "./Modules/SurveyQuestionPool/classes/class.SurveyQuestion.php"; * @extends SurveyQuestion * @ingroup ModulesSurveyQuestionPool */ -class SurveyTextQuestion extends SurveyQuestion +class SurveyTextQuestion extends SurveyQuestion { - var $maxchars; - var $textwidth; - var $textheight; - -/** -* The constructor takes possible arguments an creates an instance of the SurveyTextQuestion object. -* -* @param string $title A title string to describe the question -* @param string $description A description string to describe the question -* @param string $author A string containing the name of the questions author -* @param integer $owner A numerical ID to identify the owner/creator -* @access public -*/ - function __construct($title = "", $description = "", $author = "", $questiontext = "", $owner = -1) - { - global $DIC; - - $this->db = $DIC->database(); - parent::__construct($title, $description, $author, $questiontext, $owner); - - $this->maxchars = 0; - $this->textwidth = 50; - $this->textheight = 5; - } - - /** - * Returns the question data fields from the database - * - * @param integer $id The question ID from the database - * @return array Array containing the question fields and data from the database - * @access public - */ - function getQuestionDataArray($id) - { - $ilDB = $this->db; - $result = $ilDB->queryF("SELECT svy_question.*, " . $this->getAdditionalTableName() . ".* FROM svy_question, " . $this->getAdditionalTableName() . " WHERE svy_question.question_id = %s AND svy_question.question_id = " . $this->getAdditionalTableName() . ".question_fi", - array('integer'), - array($id) - ); - if ($result->numRows() == 1) - { - return $ilDB->fetchAssoc($result); - } - else - { - return array(); - } - } - -/** -* Loads a SurveyTextQuestion object from the database -* -* @param integer $id The database id of the text survey question -* @access public -*/ - function loadFromDb($id) - { - $ilDB = $this->db; - - $result = $ilDB->queryF("SELECT svy_question.*, " . $this->getAdditionalTableName() . ".* FROM svy_question LEFT JOIN " . $this->getAdditionalTableName() . " ON " . $this->getAdditionalTableName() . ".question_fi = svy_question.question_id WHERE svy_question.question_id = %s", - array('integer'), - array($id) - ); - if ($result->numRows() == 1) - { - $data = $ilDB->fetchAssoc($result); - $this->setId($data["question_id"]); - $this->setTitle($data["title"]); - $this->label = $data['label']; - $this->setDescription($data["description"]); - $this->setObjId($data["obj_fi"]); - $this->setAuthor($data["author"]); - $this->setOwner($data["owner_fi"]); - include_once("./Services/RTE/classes/class.ilRTE.php"); - $this->setQuestiontext(ilRTE::_replaceMediaObjectImageSrc($data["questiontext"], 1)); - $this->setObligatory($data["obligatory"]); - $this->setComplete($data["complete"]); - $this->setOriginalId($data["original_id"]); - - $this->setMaxChars($data["maxchars"]); - $this->setTextWidth($data["width"]); - $this->setTextHeight($data["height"]); + public $maxchars; + public $textwidth; + public $textheight; + + /** + * The constructor takes possible arguments an creates an instance of the SurveyTextQuestion object. + * + * @param string $title A title string to describe the question + * @param string $description A description string to describe the question + * @param string $author A string containing the name of the questions author + * @param integer $owner A numerical ID to identify the owner/creator + * @access public + */ + public function __construct($title = "", $description = "", $author = "", $questiontext = "", $owner = -1) + { + global $DIC; - } - parent::loadFromDb($id); - } + $this->db = $DIC->database(); + parent::__construct($title, $description, $author, $questiontext, $owner); + + $this->maxchars = 0; + $this->textwidth = 50; + $this->textheight = 5; + } + + /** + * Returns the question data fields from the database + * + * @param integer $id The question ID from the database + * @return array Array containing the question fields and data from the database + * @access public + */ + public function getQuestionDataArray($id) + { + $ilDB = $this->db; + $result = $ilDB->queryF( + "SELECT svy_question.*, " . $this->getAdditionalTableName() . ".* FROM svy_question, " . $this->getAdditionalTableName() . " WHERE svy_question.question_id = %s AND svy_question.question_id = " . $this->getAdditionalTableName() . ".question_fi", + array('integer'), + array($id) + ); + if ($result->numRows() == 1) { + return $ilDB->fetchAssoc($result); + } else { + return array(); + } + } + + /** + * Loads a SurveyTextQuestion object from the database + * + * @param integer $id The database id of the text survey question + * @access public + */ + public function loadFromDb($id) + { + $ilDB = $this->db; + + $result = $ilDB->queryF( + "SELECT svy_question.*, " . $this->getAdditionalTableName() . ".* FROM svy_question LEFT JOIN " . $this->getAdditionalTableName() . " ON " . $this->getAdditionalTableName() . ".question_fi = svy_question.question_id WHERE svy_question.question_id = %s", + array('integer'), + array($id) + ); + if ($result->numRows() == 1) { + $data = $ilDB->fetchAssoc($result); + $this->setId($data["question_id"]); + $this->setTitle($data["title"]); + $this->label = $data['label']; + $this->setDescription($data["description"]); + $this->setObjId($data["obj_fi"]); + $this->setAuthor($data["author"]); + $this->setOwner($data["owner_fi"]); + include_once("./Services/RTE/classes/class.ilRTE.php"); + $this->setQuestiontext(ilRTE::_replaceMediaObjectImageSrc($data["questiontext"], 1)); + $this->setObligatory($data["obligatory"]); + $this->setComplete($data["complete"]); + $this->setOriginalId($data["original_id"]); -/** -* Returns true if the question is complete for use -* -* @result boolean True if the question is complete for use, otherwise false -* @access public -*/ - function isComplete() - { - if ( - strlen($this->getTitle()) && - strlen($this->getAuthor()) && - strlen($this->getQuestiontext()) - ) - { - return 1; - } - else - { - return 0; - } - } - -/** -* Sets the maximum number of allowed characters for the text answer -* -* @access public -*/ - function setMaxChars($maxchars = 0) - { - $this->maxchars = $maxchars; - } - -/** -* Returns the maximum number of allowed characters for the text answer -* -* @access public -*/ - function getMaxChars() - { - return ($this->maxchars) ? $this->maxchars : NULL; - } - -/** -* Saves a SurveyTextQuestion object to a database -* -* @access public -*/ - function saveToDb($original_id = "") - { - $ilDB = $this->db; - - $affectedRows = parent::saveToDb($original_id); - if ($affectedRows == 1) - { - $affectedRows = $ilDB->manipulateF("DELETE FROM " . $this->getAdditionalTableName() . " WHERE question_fi = %s", - array('integer'), - array($this->getId()) - ); - $affectedRows = $ilDB->manipulateF("INSERT INTO " . $this->getAdditionalTableName() . " (question_fi, maxchars, width, height) VALUES (%s, %s, %s, %s)", - array('integer', 'integer', 'integer', 'integer'), - array($this->getId(), $this->getMaxChars(), $this->getTextWidth(), $this->getTextHeight()) - ); + $this->setMaxChars($data["maxchars"]); + $this->setTextWidth($data["width"]); + $this->setTextHeight($data["height"]); + } + parent::loadFromDb($id); + } - $this->saveMaterial(); - } - } + /** + * Returns true if the question is complete for use + * + * @result boolean True if the question is complete for use, otherwise false + * @access public + */ + public function isComplete() + { + if ( + strlen($this->getTitle()) && + strlen($this->getAuthor()) && + strlen($this->getQuestiontext()) + ) { + return 1; + } else { + return 0; + } + } + + /** + * Sets the maximum number of allowed characters for the text answer + * + * @access public + */ + public function setMaxChars($maxchars = 0) + { + $this->maxchars = $maxchars; + } + + /** + * Returns the maximum number of allowed characters for the text answer + * + * @access public + */ + public function getMaxChars() + { + return ($this->maxchars) ? $this->maxchars : null; + } + + /** + * Saves a SurveyTextQuestion object to a database + * + * @access public + */ + public function saveToDb($original_id = "") + { + $ilDB = $this->db; + + $affectedRows = parent::saveToDb($original_id); + if ($affectedRows == 1) { + $affectedRows = $ilDB->manipulateF( + "DELETE FROM " . $this->getAdditionalTableName() . " WHERE question_fi = %s", + array('integer'), + array($this->getId()) + ); + $affectedRows = $ilDB->manipulateF( + "INSERT INTO " . $this->getAdditionalTableName() . " (question_fi, maxchars, width, height) VALUES (%s, %s, %s, %s)", + array('integer', 'integer', 'integer', 'integer'), + array($this->getId(), $this->getMaxChars(), $this->getTextWidth(), $this->getTextHeight()) + ); - /** - * Returns an xml representation of the question - * - * @return string The xml representation of the question - * @access public - */ - function toXML($a_include_header = TRUE, $obligatory_state = "") - { - include_once("./Services/Xml/classes/class.ilXmlWriter.php"); - $a_xml_writer = new ilXmlWriter; - $a_xml_writer->xmlHeader(); - $this->insertXML($a_xml_writer, $a_include_header, $obligatory_state); - $xml = $a_xml_writer->xmlDumpMem(FALSE); - if (!$a_include_header) - { - $pos = strpos($xml, "?>"); - $xml = substr($xml, $pos + 2); - } - return $xml; - } - - /** - * Adds the question XML to a given XMLWriter object - * - * @param object $a_xml_writer The XMLWriter object - * @param boolean $a_include_header Determines wheather or not the XML should be used - * @access public - */ - function insertXML(&$a_xml_writer, $a_include_header = TRUE) - { - $attrs = array( - "id" => $this->getId(), - "title" => $this->getTitle(), - "type" => $this->getQuestiontype(), - "obligatory" => $this->getObligatory() - ); - $a_xml_writer->xmlStartTag("question", $attrs); - - $a_xml_writer->xmlElement("description", NULL, $this->getDescription()); - $a_xml_writer->xmlElement("author", NULL, $this->getAuthor()); - if (strlen($this->label)) - { - $attrs = array( - "label" => $this->label, - ); - } - else - { - $attrs = array(); - } - $a_xml_writer->xmlStartTag("questiontext", $attrs); - $this->addMaterialTag($a_xml_writer, $this->getQuestiontext()); - $a_xml_writer->xmlEndTag("questiontext"); + $this->saveMaterial(); + } + } - $a_xml_writer->xmlStartTag("responses"); - $attrs = array( - "id" => "0", - "rows" => $this->getTextHeight(), - "columns" => $this->getTextWidth() - ); - if ($this->getMaxChars() > 0) - { - $attrs["maxlength"] = $this->getMaxChars(); - } - $a_xml_writer->xmlElement("response_text", $attrs); - $a_xml_writer->xmlEndTag("responses"); + /** + * Returns an xml representation of the question + * + * @return string The xml representation of the question + * @access public + */ + public function toXML($a_include_header = true, $obligatory_state = "") + { + include_once("./Services/Xml/classes/class.ilXmlWriter.php"); + $a_xml_writer = new ilXmlWriter; + $a_xml_writer->xmlHeader(); + $this->insertXML($a_xml_writer, $a_include_header, $obligatory_state); + $xml = $a_xml_writer->xmlDumpMem(false); + if (!$a_include_header) { + $pos = strpos($xml, "?>"); + $xml = substr($xml, $pos + 2); + } + return $xml; + } + + /** + * Adds the question XML to a given XMLWriter object + * + * @param object $a_xml_writer The XMLWriter object + * @param boolean $a_include_header Determines wheather or not the XML should be used + * @access public + */ + public function insertXML(&$a_xml_writer, $a_include_header = true) + { + $attrs = array( + "id" => $this->getId(), + "title" => $this->getTitle(), + "type" => $this->getQuestiontype(), + "obligatory" => $this->getObligatory() + ); + $a_xml_writer->xmlStartTag("question", $attrs); + + $a_xml_writer->xmlElement("description", null, $this->getDescription()); + $a_xml_writer->xmlElement("author", null, $this->getAuthor()); + if (strlen($this->label)) { + $attrs = array( + "label" => $this->label, + ); + } else { + $attrs = array(); + } + $a_xml_writer->xmlStartTag("questiontext", $attrs); + $this->addMaterialTag($a_xml_writer, $this->getQuestiontext()); + $a_xml_writer->xmlEndTag("questiontext"); - if (count($this->material)) - { - if (preg_match("/il_(\d*?)_(\w+)_(\d+)/", $this->material["internal_link"], $matches)) - { - $attrs = array( - "label" => $this->material["title"] - ); - $a_xml_writer->xmlStartTag("material", $attrs); - $intlink = "il_" . IL_INST_ID . "_" . $matches[2] . "_" . $matches[3]; - if (strcmp($matches[1], "") != 0) - { - $intlink = $this->material["internal_link"]; - } - $a_xml_writer->xmlElement("mattext", NULL, $intlink); - $a_xml_writer->xmlEndTag("material"); - } - } - - $a_xml_writer->xmlEndTag("question"); - } + $a_xml_writer->xmlStartTag("responses"); + $attrs = array( + "id" => "0", + "rows" => $this->getTextHeight(), + "columns" => $this->getTextWidth() + ); + if ($this->getMaxChars() > 0) { + $attrs["maxlength"] = $this->getMaxChars(); + } + $a_xml_writer->xmlElement("response_text", $attrs); + $a_xml_writer->xmlEndTag("responses"); - /** - * Returns the question type of the question - * - * @return integer The question type of the question - * @access public - */ - function getQuestionType() - { - return "SurveyTextQuestion"; - } + if (count($this->material)) { + if (preg_match("/il_(\d*?)_(\w+)_(\d+)/", $this->material["internal_link"], $matches)) { + $attrs = array( + "label" => $this->material["title"] + ); + $a_xml_writer->xmlStartTag("material", $attrs); + $intlink = "il_" . IL_INST_ID . "_" . $matches[2] . "_" . $matches[3]; + if (strcmp($matches[1], "") != 0) { + $intlink = $this->material["internal_link"]; + } + $a_xml_writer->xmlElement("mattext", null, $intlink); + $a_xml_writer->xmlEndTag("material"); + } + } + + $a_xml_writer->xmlEndTag("question"); + } - /** - * Returns the name of the additional question data table in the database - * - * @return string The additional table name - * @access public - */ - function getAdditionalTableName() - { - return "svy_qst_text"; - } - - /** - * Creates the user data of the svy_answer table from the POST data - * - * @return array User data according to the svy_answer table - * @access public - */ - function &getWorkingDataFromUserInput($post_data) - { - $entered_value = $post_data[$this->getId() . "_text_question"]; - $data = array(); - if (strlen($entered_value)) - { - array_push($data, array("textanswer" => $entered_value)); - } - return $data; - } - - /** - * Checks the input of the active user for obligatory status - * and entered values - * - * @param array $post_data The contents of the $_POST array - * @param integer $survey_id The database ID of the active survey - * @return string Empty string if the input is ok, an error message otherwise - * @access public - */ - function checkUserInput($post_data, $survey_id) - { - $entered_value = $post_data[$this->getId() . "_text_question"]; - - if ((!$this->getObligatory($survey_id)) && (strlen($entered_value) == 0)) return ""; - - if (strlen($entered_value) == 0) return $this->lng->txt("text_question_not_filled_out"); + /** + * Returns the question type of the question + * + * @return integer The question type of the question + * @access public + */ + public function getQuestionType() + { + return "SurveyTextQuestion"; + } - // see bug #22648 - include_once("./Services/Utilities/classes/class.ilStr.php"); - if ($this->getMaxChars() > 0 && ilStr::strLen($entered_value) > $this->getMaxChars()) - { - return str_replace("%s", ilStr::strLen($entered_value), $this->lng->txt("svy_answer_too_long")); - } + /** + * Returns the name of the additional question data table in the database + * + * @return string The additional table name + * @access public + */ + public function getAdditionalTableName() + { + return "svy_qst_text"; + } + + /** + * Creates the user data of the svy_answer table from the POST data + * + * @return array User data according to the svy_answer table + * @access public + */ + public function &getWorkingDataFromUserInput($post_data) + { + $entered_value = $post_data[$this->getId() . "_text_question"]; + $data = array(); + if (strlen($entered_value)) { + array_push($data, array("textanswer" => $entered_value)); + } + return $data; + } + + /** + * Checks the input of the active user for obligatory status + * and entered values + * + * @param array $post_data The contents of the $_POST array + * @param integer $survey_id The database ID of the active survey + * @return string Empty string if the input is ok, an error message otherwise + * @access public + */ + public function checkUserInput($post_data, $survey_id) + { + $entered_value = $post_data[$this->getId() . "_text_question"]; + + if ((!$this->getObligatory($survey_id)) && (strlen($entered_value) == 0)) { + return ""; + } + + if (strlen($entered_value) == 0) { + return $this->lng->txt("text_question_not_filled_out"); + } - return ""; - } - - function saveUserInput($post_data, $active_id, $a_return = false) - { - $ilDB = $this->db; + // see bug #22648 + include_once("./Services/Utilities/classes/class.ilStr.php"); + if ($this->getMaxChars() > 0 && ilStr::strLen($entered_value) > $this->getMaxChars()) { + return str_replace("%s", ilStr::strLen($entered_value), $this->lng->txt("svy_answer_too_long")); + } - $entered_value = $this->stripSlashesAddSpaceFallback($post_data[$this->getId() . "_text_question"]); - $maxchars = $this->getMaxChars(); + return ""; + } + + public function saveUserInput($post_data, $active_id, $a_return = false) + { + $ilDB = $this->db; - include_once("./Services/Utilities/classes/class.ilStr.php"); - if ($maxchars > 0) - { - $entered_value = ilStr::subStr($entered_value, 0, $maxchars); - } - - if($a_return) - { - return array(array("value"=>null, "textanswer"=>$entered_value)); - } - if (strlen($entered_value) == 0) return; - - $next_id = $ilDB->nextId('svy_answer'); - #20216 - $fields = array(); - $fields['answer_id'] = array("integer", $next_id); - $fields['question_fi'] = array("integer", $this->getId()); - $fields['active_fi'] = array("integer", $active_id); - $fields['value'] = array("float", NULL); - $fields['textanswer'] = array("clob", (strlen($entered_value)) ? $entered_value : NULL); - $fields['tstamp'] = array("integer", time()); + $entered_value = $this->stripSlashesAddSpaceFallback($post_data[$this->getId() . "_text_question"]); + $maxchars = $this->getMaxChars(); - $affectedRows = $ilDB->insert("svy_answer", $fields); + include_once("./Services/Utilities/classes/class.ilStr.php"); + if ($maxchars > 0) { + $entered_value = ilStr::subStr($entered_value, 0, $maxchars); + } + + if ($a_return) { + return array(array("value"=>null, "textanswer"=>$entered_value)); + } + if (strlen($entered_value) == 0) { + return; + } + + $next_id = $ilDB->nextId('svy_answer'); + #20216 + $fields = array(); + $fields['answer_id'] = array("integer", $next_id); + $fields['question_fi'] = array("integer", $this->getId()); + $fields['active_fi'] = array("integer", $active_id); + $fields['value'] = array("float", null); + $fields['textanswer'] = array("clob", (strlen($entered_value)) ? $entered_value : null); + $fields['tstamp'] = array("integer", time()); - } - - /** - * Import response data from the question import file - * - * @return array $a_data Array containing the response data - * @access public - */ - function importResponses($a_data) - { - foreach ($a_data as $id => $data) - { - if ($data["maxlength"] > 0) - { - $this->setMaxChars($data["maxlength"]); - } - if ($data["rows"] > 0) - { - $this->setTextHeight($data["rows"]); - } - if ($data["columns"] > 0) - { - $this->setTextWidth($data["columns"]); - } - } - } + $affectedRows = $ilDB->insert("svy_answer", $fields); + } + + /** + * Import response data from the question import file + * + * @return array $a_data Array containing the response data + * @access public + */ + public function importResponses($a_data) + { + foreach ($a_data as $id => $data) { + if ($data["maxlength"] > 0) { + $this->setMaxChars($data["maxlength"]); + } + if ($data["rows"] > 0) { + $this->setTextHeight($data["rows"]); + } + if ($data["columns"] > 0) { + $this->setTextWidth($data["columns"]); + } + } + } - /** - * Returns if the question is usable for preconditions - * - * @return boolean TRUE if the question is usable for a precondition, FALSE otherwise - * @access public - */ - function usableForPrecondition() - { - return FALSE; - } + /** + * Returns if the question is usable for preconditions + * + * @return boolean TRUE if the question is usable for a precondition, FALSE otherwise + * @access public + */ + public function usableForPrecondition() + { + return false; + } - /** - * Returns the width of the answer field - * - * @return integer The width of the answer field in characters - * @access public - */ - function getTextWidth() - { - return ($this->textwidth) ? $this->textwidth : NULL; - } - - /** - * Returns the height of the answer field - * - * @return integer The height of the answer field in characters - * @access public - */ - function getTextHeight() - { - return ($this->textheight) ? $this->textheight : NULL; - } - - /** - * Sets the width of the answer field - * - * @param integer $a_textwidth The width of the answer field in characters - * @access public - */ - function setTextWidth($a_textwidth) - { - if ($a_textwidth < 1) - { - $this->textwidth = 50; - } - else - { - $this->textwidth = $a_textwidth; - } - } - - /** - * Sets the height of the answer field - * - * @param integer $a_textheight The height of the answer field in characters - * @access public - */ - function setTextHeight($a_textheight) - { - if ($a_textheight < 1) - { - $this->textheight = 5; - } - else - { - $this->textheight = $a_textheight; - } - } + /** + * Returns the width of the answer field + * + * @return integer The width of the answer field in characters + * @access public + */ + public function getTextWidth() + { + return ($this->textwidth) ? $this->textwidth : null; + } + + /** + * Returns the height of the answer field + * + * @return integer The height of the answer field in characters + * @access public + */ + public function getTextHeight() + { + return ($this->textheight) ? $this->textheight : null; + } + + /** + * Sets the width of the answer field + * + * @param integer $a_textwidth The width of the answer field in characters + * @access public + */ + public function setTextWidth($a_textwidth) + { + if ($a_textwidth < 1) { + $this->textwidth = 50; + } else { + $this->textwidth = $a_textwidth; + } + } + + /** + * Sets the height of the answer field + * + * @param integer $a_textheight The height of the answer field in characters + * @access public + */ + public function setTextHeight($a_textheight) + { + if ($a_textheight < 1) { + $this->textheight = 5; + } else { + $this->textheight = $a_textheight; + } + } } -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/class.SurveyTextQuestionEvaluation.php b/Modules/SurveyQuestionPool/classes/class.SurveyTextQuestionEvaluation.php index 0181cd8b88e4eb0d1c8bff07f3054f34a0a310f0..5a494a81ce699902d206911163537124b13bdd38 100644 --- a/Modules/SurveyQuestionPool/classes/class.SurveyTextQuestionEvaluation.php +++ b/Modules/SurveyQuestionPool/classes/class.SurveyTextQuestionEvaluation.php @@ -4,47 +4,41 @@ include_once "Modules/SurveyQuestionPool/classes/class.SurveyQuestionEvaluation.php"; /** - * Survey text evaluation + * Survey text evaluation * * @author Jörg Lützenkirchen$error_message
"); - } - if ($this->object->getMaxChars()) - { - $template->setVariable("TEXT_MAXCHARS", sprintf($this->lng->txt("text_maximum_chars_allowed"), $this->object->getMaxChars())); - } - $template->parseCurrentBlock(); - return $template->get(); - } + if ($this->object->getTextHeight() == 1) { + $template->setCurrentBlock("textinput"); + if (is_array($working_data)) { + if (strlen($working_data[0]["textanswer"])) { + $template->setVariable("VALUE_ANSWER", " value=\"" . ilUtil::prepareFormOutput($working_data[0]["textanswer"]) . "\""); + } + } + $template->setVariable("QUESTION_ID", $this->object->getId()); + $template->setVariable("WIDTH", $this->object->getTextWidth()); + if ($this->object->getMaxChars()) { + $template->setVariable("MAXLENGTH", " maxlength=\"" . $this->object->getMaxChars() . "\""); + } + $template->parseCurrentBlock(); + } else { + $template->setCurrentBlock("textarea"); + if (is_array($working_data)) { + $template->setVariable("VALUE_ANSWER", ilUtil::prepareFormOutput($working_data[0]["textanswer"])); + } + $template->setVariable("QUESTION_ID", $this->object->getId()); + $template->setVariable("WIDTH", $this->object->getTextWidth()); + $template->setVariable("HEIGHT", $this->object->getTextHeight()); + $template->parseCurrentBlock(); + } + $template->setCurrentBlock("question_data_text"); + if ($show_questiontext) { + $this->outQuestionText($template); + } + if ($question_title) { + $template->setVariable("QUESTION_TITLE", $this->object->getTitle()); + } + $template->setVariable("TEXT_ANSWER", $this->lng->txt("answer")); + $template->setVariable("LABEL_QUESTION_ID", $this->object->getId()); + if (strcmp($error_message, "") != 0) { + $template->setVariable("ERROR_MESSAGE", "$error_message
"); + } + if ($this->object->getMaxChars()) { + $template->setVariable("TEXT_MAXCHARS", sprintf($this->lng->txt("text_maximum_chars_allowed"), $this->object->getMaxChars())); + } + $template->parseCurrentBlock(); + return $template->get(); + } } - -?> \ No newline at end of file diff --git a/Modules/SurveyQuestionPool/classes/class.ilCategoryWizardInputGUI.php b/Modules/SurveyQuestionPool/classes/class.ilCategoryWizardInputGUI.php index bd492e6ab1313d2acc3c1a74d12df5694cbc0697..9b87b986a0de4b43a8c3b658ee3957e6da3d6f70 100644 --- a/Modules/SurveyQuestionPool/classes/class.ilCategoryWizardInputGUI.php +++ b/Modules/SurveyQuestionPool/classes/class.ilCategoryWizardInputGUI.php @@ -1,472 +1,435 @@ +* @author Helmut Schottmüller'.implode("",$scan_log).''; - $this->tpl->setVariable("ADM_CONTENT", $scan_log); - } - else - { - $scan_log = "no scanlog found."; - } - - // output - $this->tpl->addBlockFile("ADM_CONTENT", "adm_content", "tpl.adm_scan.html", - "Modules/SystemFolder"); - $this->tpl->setVariable("TXT_TITLE", $this->lng->txt("scan_details")); - $this->tpl->setVariable("COLSPAN", 3); - $this->tpl->setVariable("TXT_SCAN_LOG", $scan_log); - $this->tpl->setVariable("TXT_DONE", $this->lng->txt("done")); - } - - - /** - * Benchmark settings - */ - function benchmarkObject() - { - $rbacsystem = $this->rbacsystem; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - $tpl = $this->tpl; - $ilErr = $this->error; - - if (!$rbacsystem->checkAccess("visible,read",$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt("permission_denied"),$ilErr->MESSAGE); - } - - $this->benchmarkSubTabs("settings"); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // Activate DB Benchmark - $cb = new ilCheckboxInputGUI($lng->txt("adm_activate_db_benchmark"), "enable_db_bench"); - $cb->setChecked($ilSetting->get("enable_db_bench")); - $cb->setInfo($lng->txt("adm_activate_db_benchmark_desc")); - $this->form->addItem($cb); - - // DB Benchmark User - $ti = new ilTextInputGUI($lng->txt("adm_db_benchmark_user"), "db_bench_user"); - $ti->setValue($ilSetting->get("db_bench_user")); - $ti->setInfo($lng->txt("adm_db_benchmark_user_desc")); - $this->form->addItem($ti); - - $this->form->addCommandButton("saveBenchSettings", $lng->txt("save")); - - $this->form->setTitle($lng->txt("adm_db_benchmark")); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - - $tpl->setContent($this->form->getHTML()); - } - - /** - * Show db benchmark results - */ - function showDbBenchChronologicalObject() - { - $this->benchmarkSubTabs("chronological"); - $this->showDbBenchResults("chronological"); - } - - /** - * Show db benchmark results - */ - function showDbBenchSlowestFirstObject() - { - $this->benchmarkSubTabs("slowest_first"); - $this->showDbBenchResults("slowest_first"); - } - - /** - * Show db benchmark results - */ - function showDbBenchSortedBySqlObject() - { - $this->benchmarkSubTabs("sorted_by_sql"); - $this->showDbBenchResults("sorted_by_sql"); - } - - /** - * Show db benchmark results - */ - function showDbBenchByFirstTableObject() - { - $this->benchmarkSubTabs("by_first_table"); - $this->showDbBenchResults("by_first_table"); - } - - /** - * Show Db Benchmark Results - * - * @param string mode - */ - function showDbBenchResults($a_mode) - { - $tpl = $this->tpl; - - $ilBench = $this->bench; - $rec = $ilBench->getDbBenchRecords(); - - include_once("./Modules/SystemFolder/classes/class.ilBenchmarkTableGUI.php"); - $table = new ilBenchmarkTableGUI($this, "benchmark", $rec, $a_mode); - $tpl->setContent($table->getHTML()); - } - - /** - * Benchmark sub tabs - * - * @param - * @return - */ - function benchmarkSubTabs($a_current) - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilBench = $this->bench; - $ilTabs->activateTab("benchmarks"); // #18083 - - $ilTabs->addSubtab("settings", - $lng->txt("settings"), - $ilCtrl->getLinkTarget($this, "benchmark")); - - $rec = $ilBench->getDbBenchRecords(); - if (count($rec) > 0) - { - $ilTabs->addSubtab("chronological", - $lng->txt("adm_db_bench_chronological"), - $ilCtrl->getLinkTarget($this, "showDbBenchChronological")); - $ilTabs->addSubtab("slowest_first", - $lng->txt("adm_db_bench_slowest_first"), - $ilCtrl->getLinkTarget($this, "showDbBenchSlowestFirst")); - $ilTabs->addSubtab("sorted_by_sql", - $lng->txt("adm_db_bench_sorted_by_sql"), - $ilCtrl->getLinkTarget($this, "showDbBenchSortedBySql")); - $ilTabs->addSubtab("by_first_table", - $lng->txt("adm_db_bench_by_first_table"), - $ilCtrl->getLinkTarget($this, "showDbBenchByFirstTable")); - } - - $ilTabs->activateSubTab($a_current); - } - - - /** - * Save benchmark settings - */ - function saveBenchSettingsObject() - { - $ilBench = $this->bench; - if ($_POST["enable_db_bench"]) - { - $ilBench->enableDbBench(true, ilUtil::stripSlashes($_POST["db_bench_user"])); - } - else - { - $ilBench->enableDbBench(false); - } - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - - $this->ctrl->redirect($this, "benchmark"); - } - - - /** - * save benchmark settings - */ - function switchBenchModuleObject() - { - $this->ctrl->setParameter($this,'cur_mod',$_POST['module']); - $this->ctrl->redirect($this, "benchmark"); - } - - - /** - * delete all benchmark records - */ - function clearBenchObject() - { - $ilBench = $this->bench; - $ilBench->clearData(); - $this->saveBenchSettingsObject(); - - } - - // get tabs - function getAdminTabs() - { - $rbacsystem = $this->rbacsystem; - $ilHelp = $this->help; - -// $ilHelp->setScreenIdComponent($this->object->getType()); - - $this->ctrl->setParameter($this,"ref_id",$this->object->getRefId()); - - // general settings - if ($rbacsystem->checkAccess("write",$this->object->getRefId())) - { - $this->tabs_gui->addTarget("general_settings", - $this->ctrl->getLinkTarget($this, "showBasicSettings"), - array("showBasicSettings", "saveBasicSettings"), get_class($this)); - } - - // server info - if ($rbacsystem->checkAccess("visible,read",$this->object->getRefId())) - { - $this->tabs_gui->addTarget("server", - $this->ctrl->getLinkTarget($this, "showServerInfo"), - array("showServerInfo", "view"), get_class($this)); - } - - if ($rbacsystem->checkAccess("write",$this->object->getRefId())) - { - $this->tabs_gui->addTarget("cron_jobs", - $this->ctrl->getLinkTargetByClass("ilCronManagerGUI", ""), "", get_class($this)); - -// $tabs_gui->addTarget("system_check", -// $this->ctrl->getLinkTarget($this, "check"), array("check","viewScanLog","saveCheckParams","saveCheckCron"), get_class($this)); - - $this->tabs_gui->addTarget("benchmarks", - $this->ctrl->getLinkTarget($this, "benchmark"), "benchmark", get_class($this)); - } - - if ($rbacsystem->checkAccess('edit_permission',$this->object->getRefId())) - { - $this->tabs_gui->addTarget("perm_settings", - $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), array("perm","info","owner"), 'ilpermissiongui'); - } - } - - /** - * Show PHP Information - */ - function showPHPInfoObject() - { - phpinfo(); - exit; - } - - // - // - // Server Info - // - // - - /** - * Set sub tabs for server info - */ - function setServerInfoSubTabs($a_activate) - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $rbacsystem = $this->rbacsystem; - - $ilTabs->addSubTabTarget("server_data", $ilCtrl->getLinkTarget($this, "showServerInfo")); - - if ($rbacsystem->checkAccess("write",$this->object->getRefId())) - { - $ilTabs->addSubTabTarget("adm_https", $ilCtrl->getLinkTarget($this, "showHTTPS")); - $ilTabs->addSubTabTarget("proxy", $ilCtrl->getLinkTarget($this, "showProxy")); - $ilTabs->addSubTabTarget("java_server", $ilCtrl->getLinkTarget($this, "showJavaServer")); - $ilTabs->addSubTabTarget("webservices", $ilCtrl->getLinkTarget($this, "showWebServices")); - } - - $ilTabs->setSubTabActive($a_activate); - $ilTabs->setTabActive("server"); - } - - /** - * Show server info - */ - function showServerInfoObject() - { - /** - * @var $ilToolbar ilToolbarGUI - * @var $lng ilLanguage - * @var $ilCtrl ilCtrl - * @var $tpl ilTemplate - */ - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $ilToolbar = $this->toolbar; - $lng = $this->lng; - - require_once 'Services/UIComponent/Button/classes/class.ilLinkButton.php'; - $button = ilLinkButton::getInstance(); - $button->setCaption('vc_information'); - $button->setUrl($this->ctrl->getLinkTarget($this, 'showVcsInformation')); - $ilToolbar->addButtonInstance($button); - - $this->initServerInfoForm(); - $this->setServerInfoSubTabs("server_data"); - - $btpl = new ilTemplate("tpl.server_data.html", true, true, "Modules/SystemFolder"); - $btpl->setVariable("FORM", $this->form->getHTML()); - $btpl->setVariable("PHP_INFO_TARGET", $ilCtrl->getLinkTarget($this, "showPHPInfo")); - $tpl->setContent($btpl->get()); - } - - /** - * Init server info form. - * - * @param int $a_mode Edit Mode - */ - public function initServerInfoForm() - { - $lng = $this->lng; - $ilClientIniFile = $this->client_ini; - $ilSetting = $this->settings; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // installation name - $ne = new ilNonEditableValueGUI($lng->txt("inst_name"), ""); - $ne->setValue($ilClientIniFile->readVariable("client","name")); - $ne->setInfo($ilClientIniFile->readVariable("client","description")); - $this->form->addItem($ne); - - // client id - $ne = new ilNonEditableValueGUI($lng->txt("client_id"), ""); - $ne->setValue(CLIENT_ID); - $this->form->addItem($ne); - - // installation id - $ne = new ilNonEditableValueGUI($lng->txt("inst_id"), ""); - $ne->setValue($ilSetting->get("inst_id")); - $this->form->addItem($ne); - - // database version - $ne = new ilNonEditableValueGUI($lng->txt("db_version"), ""); - $ne->setValue($ilSetting->get("db_version")); - - include_once ("./Services/Database/classes/class.ilDBUpdate.php"); - $this->form->addItem($ne); - - // ilias version - $ne = new ilNonEditableValueGUI($lng->txt("ilias_version"), ""); - $ne->setValue($ilSetting->get("ilias_version")); - $this->form->addItem($ne); - - // host - $ne = new ilNonEditableValueGUI($lng->txt("host"), ""); - $ne->setValue($_SERVER["SERVER_NAME"]); - $this->form->addItem($ne); - - // ip & port - $ne = new ilNonEditableValueGUI($lng->txt("ip_address")." & ".$this->lng->txt("port"), ""); - $ne->setValue($_SERVER["SERVER_ADDR"].":".$_SERVER["SERVER_PORT"]); - $this->form->addItem($ne); - - // server - $ne = new ilNonEditableValueGUI($lng->txt("server_software"), ""); - $ne->setValue($_SERVER["SERVER_SOFTWARE"]); - $this->form->addItem($ne); - - // http path - $ne = new ilNonEditableValueGUI($lng->txt("http_path"), ""); - $ne->setValue(ILIAS_HTTP_PATH); - $this->form->addItem($ne); - - // absolute path - $ne = new ilNonEditableValueGUI($lng->txt("absolute_path"), ""); - $ne->setValue(ILIAS_ABSOLUTE_PATH); - $this->form->addItem($ne); - - $not_set = $lng->txt("path_not_set"); - - // convert - $ne = new ilNonEditableValueGUI($lng->txt("path_to_convert"), ""); - $ne->setValue((PATH_TO_CONVERT) ? PATH_TO_CONVERT : $not_set); - $this->form->addItem($ne); - - // zip - $ne = new ilNonEditableValueGUI($lng->txt("path_to_zip"), ""); - $ne->setValue((PATH_TO_ZIP) ? PATH_TO_ZIP : $not_set); - $this->form->addItem($ne); - - // unzip - $ne = new ilNonEditableValueGUI($lng->txt("path_to_unzip"), ""); - $ne->setValue((PATH_TO_UNZIP) ? PATH_TO_UNZIP : $not_set); - $this->form->addItem($ne); - - // java - $ne = new ilNonEditableValueGUI($lng->txt("path_to_java"), ""); - $ne->setValue((PATH_TO_JAVA) ? PATH_TO_JAVA : $not_set); - $this->form->addItem($ne); - - // mkisofs - $ne = new ilNonEditableValueGUI($lng->txt("path_to_mkisofs"), ""); - $ne->setValue((PATH_TO_MKISOFS) ? PATH_TO_MKISOFS : $not_set); - $this->form->addItem($ne); - - // latex - $ne = new ilNonEditableValueGUI($lng->txt("url_to_latex"), ""); - $ne->setValue((URL_TO_LATEX) ? URL_TO_LATEX : $not_set); - $this->form->addItem($ne); - - - $this->form->setTitle($lng->txt("server_data")); - $this->form->setFormAction($this->ctrl->getFormAction($this)); - - } - - // - // - // General Settings - // - // - - /** - * Set sub tabs for general settings - */ - function setGeneralSettingsSubTabs($a_activate) - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - - $ilTabs->addSubTabTarget("basic_settings", $ilCtrl->getLinkTarget($this, "showBasicSettings")); - $ilTabs->addSubTabTarget("header_title", $ilCtrl->getLinkTarget($this, "showHeaderTitle")); - $ilTabs->addSubTabTarget("contact_data", $ilCtrl->getLinkTarget($this, "showContactInformation")); - $ilTabs->addSubTabTarget("adm_imprint", $ilCtrl->getLinkTargetByClass("ilimprintgui", "preview")); - - $ilTabs->setSubTabActive($a_activate); - $ilTabs->setTabActive("general_settings"); - } - - // - // - // Basic Settings - // - // - - /** - * Show basic settings - */ - function showBasicSettingsObject() - { - $tpl = $this->tpl; - - $this->initBasicSettingsForm(); - $this->setGeneralSettingsSubTabs("basic_settings"); - - $tpl->setContent($this->form->getHTML()); - } - - - /** - * Init basic settings form. - */ - public function initBasicSettingsForm() - { - /** - * @var $lng ilLanguage - * @var $ilSetting ilSetting - */ - $lng = $this->lng; - $ilSetting = $this->settings; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - $lng->loadLanguageModule("pd"); - - // installation short title - $ti = new ilTextInputGUI($this->lng->txt("short_inst_name"), "short_inst_name"); - $ti->setMaxLength(200); - $ti->setSize(40); - $ti->setValue($ilSetting->get("short_inst_name")); - $ti->setInfo($this->lng->txt("short_inst_name_info")); - $this->form->addItem($ti); - - - $cb = new ilCheckboxInputGUI($this->lng->txt("pub_section"), "pub_section"); - $cb->setInfo($lng->txt("pub_section_info")); - if (ilPublicSectionSettings::getInstance()->isEnabled()) - { - $cb->setChecked(true); - } - $this->form->addItem($cb); - - $this->lng->loadLanguageModule('administration'); - $domains = new ilTextInputGUI($this->lng->txt('adm_pub_section_domain_filter'), 'public_section_domains'); - $domains->setInfo($this->lng->txt('adm_pub_section_domain_filter_info')); - $domains->setMulti(true); - $domains->setValue(current(ilPublicSectionSettings::getInstance()->getDomains())); - $domains->setMultiValues(ilPublicSectionSettings::getInstance()->getDomains()); - - $cb->addSubItem($domains); - - - // Enable Global Profiles - $cb_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_user_publish'), 'enable_global_profiles'); - $cb_prop->setInfo($lng->txt('pd_enable_user_publish_info')); - $cb_prop->setChecked($ilSetting->get('enable_global_profiles')); - $cb->addSubItem($cb_prop); - - // search engine - include_once('Services/PrivacySecurity/classes/class.ilRobotSettings.php'); - $robot_settings = ilRobotSettings::_getInstance(); - $cb2 = new ilCheckboxInputGUI($this->lng->txt("search_engine"), "open_google"); - $cb2->setInfo($this->lng->txt("enable_search_engine")); - $this->form->addItem($cb2); - - if(!$robot_settings->checkRewrite()) - { - $cb2->setAlert($lng->txt("allow_override_alert")); - $cb2->setChecked(false); - $cb2->setDisabled(true); - } - else - { - if ($ilSetting->get("open_google")) - { - $cb2->setChecked(true); - } - } - - // locale - $ti = new ilTextInputGUI($this->lng->txt("adm_locale"), "locale"); - $ti->setMaxLength(80); - $ti->setSize(40); - $ti->setInfo($this->lng->txt("adm_locale_info")); - $ti->setValue($ilSetting->get("locale")); - $this->form->addItem($ti); - - // save and cancel commands - $this->form->addCommandButton("saveBasicSettings", $lng->txt("save")); - - $this->form->setTitle($lng->txt("basic_settings")); - $this->form->setFormAction($this->ctrl->getFormAction($this)); - - } - - /** - * Save basic settings form - * - */ - public function saveBasicSettingsObject() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - - if (!$rbacsystem->checkAccess("write",$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt("permission_denied"),$ilErr->MESSAGE); - } - - $this->initBasicSettingsForm(); - if ($this->form->checkInput()) - { - $ilSetting->set("short_inst_name", $_POST["short_inst_name"]); - - $public_section = ilPublicSectionSettings::getInstance(); - $public_section->setEnabled($this->form->getInput('pub_section')); - - $domains = array(); - foreach((array) $this->form->getInput('public_section_domains') as $domain) - { - if(strlen(trim($domain))) - { - $domains[] = $domain; - } - } - $public_section->setDomains($domains); - $public_section->save(); - - $global_profiles = ($_POST["pub_section"]) - ? (int)$_POST['enable_global_profiles'] - : 0; - $ilSetting->set('enable_global_profiles', $global_profiles); - - $ilSetting->set("open_google", $_POST["open_google"]); - $ilSetting->set("locale", $_POST["locale"]); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "showBasicSettings"); - } - $this->setGeneralSettingsSubTabs("basic_settings"); - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - - // - // - // Header title - // - // - - /** - * Show header title - */ - function showHeaderTitleObject($a_get_post_values = false) - { - $tpl = $this->tpl; - - $this->setGeneralSettingsSubTabs("header_title"); - include_once("./Services/Object/classes/class.ilObjectTranslationTableGUI.php"); - $table = new ilObjectTranslationTableGUI($this, "showHeaderTitle", false); - if ($a_get_post_values) - { - $vals = array(); - foreach($_POST["title"] as $k => $v) - { - $vals[] = array("title" => $v, - "desc" => $_POST["desc"][$k], - "lang" => $_POST["lang"][$k], - "default" => ($_POST["default"] == $k)); - } - $table->setData($vals); - } - else - { - $data = $this->object->getHeaderTitleTranslations(); - if (is_array($data["Fobject"])) - { - foreach($data["Fobject"] as $k => $v) - { - if ($k == $data["default_language"]) - { - $data["Fobject"][$k]["default"] = true; - } - else - { - $data["Fobject"][$k]["default"] = false; - } - } - } - else - { - $data["Fobject"] = array(); - } - $table->setData($data["Fobject"]); - } - $tpl->setContent($table->getHTML()); - } - - /** - * Save header titles - */ - function saveHeaderTitlesObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - - if (!$rbacsystem->checkAccess("write",$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt("permission_denied"),$ilErr->MESSAGE); - } - -// var_dump($_POST); - - // default language set? - if (!isset($_POST["default"]) && count($_POST["lang"]) > 0) - { - ilUtil::sendFailure($lng->txt("msg_no_default_language")); - return $this->showHeaderTitleObject(true); - } - - // all languages set? - if (array_key_exists("",$_POST["lang"])) - { - ilUtil::sendFailure($lng->txt("msg_no_language_selected")); - return $this->showHeaderTitleObject(true); - } - - // no single language is selected more than once? - if (count(array_unique($_POST["lang"])) < count($_POST["lang"])) - { - ilUtil::sendFailure($lng->txt("msg_multi_language_selected")); - return $this->showHeaderTitleObject(true); - } - - // save the stuff - $this->object->removeHeaderTitleTranslations(); - foreach($_POST["title"] as $k => $v) - { - $this->object->addHeaderTitleTranslation( - ilUtil::stripSlashes($v), - ilUtil::stripSlashes($_POST["desc"][$k]), - ilUtil::stripSlashes($_POST["lang"][$k]), - ($_POST["default"] == $k)); - } - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "showHeaderTitle"); - } - - /** - * Add a header title - */ - function addHeaderTitleObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (is_array($_POST["title"])) - { - foreach($_POST["title"] as $k => $v) {} - } - $k++; - $_POST["title"][$k] = ""; - $this->showHeaderTitleObject(true); - } - - /** - * Remove header titles - */ - function deleteHeaderTitlesObject() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; -//var_dump($_POST); - foreach($_POST["title"] as $k => $v) - { - if ($_POST["check"][$k]) - { - unset($_POST["title"][$k]); - unset($_POST["desc"][$k]); - unset($_POST["lang"][$k]); - if ($k == $_POST["default"]) - { - unset($_POST["default"]); - } - } - } - $this->saveHeaderTitlesObject(); - } - - - // - // - // Cron Jobs - // - // - - /* - * OLD GLOBAL CRON JOB SWITCHES (ilSetting) - * - * cron_user_check => obsolete - * cron_inactive_user_delete => obsolete - * cron_inactivated_user_delete => obsolete - * cron_link_check => obsolete - * cron_web_resource_check => migrated - * cron_lucene_index => obsolete - * forum_notification => migrated - * mail_notification => migrated - * disk_quota/enabled => migrated - * crsgrp_ntf => migrated - * cron_upd_adrbook => migrated - */ - - function jumpToCronJobsObject() - { - // #13010 - this is used for external settings - $this->ctrl->redirectByClass("ilCronManagerGUI", "render"); - } - - - // - // - // Contact Information - // - // - - /** - * Show contact information - */ - function showContactInformationObject() - { - $tpl = $this->tpl; - - $this->initContactInformationForm(); - $this->setGeneralSettingsSubTabs("contact_data"); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Init contact information form. - */ - public function initContactInformationForm() - { - $lng = $this->lng; - $ilSetting = $this->settings; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // first name - $ti = new ilTextInputGUI($this->lng->txt("firstname"), "admin_firstname"); - $ti->setMaxLength(64); - $ti->setSize(40); - $ti->setRequired(true); - $ti->setValue($ilSetting->get("admin_firstname")); - $this->form->addItem($ti); - - // last name - $ti = new ilTextInputGUI($this->lng->txt("lastname"), "admin_lastname"); - $ti->setMaxLength(64); - $ti->setSize(40); - $ti->setRequired(true); - $ti->setValue($ilSetting->get("admin_lastname")); - $this->form->addItem($ti); - - // title - $ti = new ilTextInputGUI($this->lng->txt("title"), "admin_title"); - $ti->setMaxLength(64); - $ti->setSize(40); - $ti->setValue($ilSetting->get("admin_title")); - $this->form->addItem($ti); - - // position - $ti = new ilTextInputGUI($this->lng->txt("position"), "admin_position"); - $ti->setMaxLength(64); - $ti->setSize(40); - $ti->setValue($ilSetting->get("admin_position")); - $this->form->addItem($ti); - - // institution - $ti = new ilTextInputGUI($this->lng->txt("institution"), "admin_institution"); - $ti->setMaxLength(200); - $ti->setSize(40); - $ti->setValue($ilSetting->get("admin_institution")); - $this->form->addItem($ti); - - // street - $ti = new ilTextInputGUI($this->lng->txt("street"), "admin_street"); - $ti->setMaxLength(64); - $ti->setSize(40); - //$ti->setRequired(true); - $ti->setValue($ilSetting->get("admin_street")); - $this->form->addItem($ti); - - // zip code - $ti = new ilTextInputGUI($this->lng->txt("zipcode"), "admin_zipcode"); - $ti->setMaxLength(10); - $ti->setSize(5); - //$ti->setRequired(true); - $ti->setValue($ilSetting->get("admin_zipcode")); - $this->form->addItem($ti); - - // city - $ti = new ilTextInputGUI($this->lng->txt("city"), "admin_city"); - $ti->setMaxLength(64); - $ti->setSize(40); - //$ti->setRequired(true); - $ti->setValue($ilSetting->get("admin_city")); - $this->form->addItem($ti); - - // country - $ti = new ilTextInputGUI($this->lng->txt("country"), "admin_country"); - $ti->setMaxLength(64); - $ti->setSize(40); - //$ti->setRequired(true); - $ti->setValue($ilSetting->get("admin_country")); - $this->form->addItem($ti); - - // phone - $ti = new ilTextInputGUI($this->lng->txt("phone"), "admin_phone"); - $ti->setMaxLength(64); - $ti->setSize(40); - //$ti->setRequired(true); - $ti->setValue($ilSetting->get("admin_phone")); - $this->form->addItem($ti); - - // email - $ti = new ilEmailInputGUI($this->lng->txt("email"), "admin_email"); - $ti->setMaxLength(64); - $ti->setSize(40); - $ti->setRequired(true); - $ti->allowRFC822(true); - $ti->setValue($ilSetting->get("admin_email")); - $this->form->addItem($ti); - - // feedback recipient - /* currently used in: - - footer - - terms of service: no document found message - */ - /*$ti = new ilEmailInputGUI($this->lng->txt("feedback_recipient"), "feedback_recipient"); - $ti->setInfo(sprintf($this->lng->txt("feedback_recipient_info"), $this->lng->txt("contact_sysadmin"))); - $ti->setMaxLength(64); - $ti->setSize(40); - $ti->setRequired(true); - $ti->allowRFC822(true); - $ti->setValue($ilSetting->get("feedback_recipient")); - $this->form->addItem($ti);*/ - - // System support contacts - include_once("./Modules/SystemFolder/classes/class.ilSystemSupportContacts.php"); - $ti = new ilTextInputGUI($this->lng->txt("adm_support_contacts"), "adm_support_contacts"); - $ti->setMaxLength(500); - $ti->setValue(ilSystemSupportContacts::getList()); - //$ti->setSize(); - $ti->setInfo($this->lng->txt("adm_support_contacts_info")); - $this->form->addItem($ti); - - - // error recipient - /*$ti = new ilEmailInputGUI($this->lng->txt("error_recipient"), "error_recipient"); - $ti->setMaxLength(64); - $ti->setSize(40); - $ti->allowRFC822(true); - $ti->setValue($ilSetting->get("error_recipient")); - $this->form->addItem($ti);*/ - - $this->form->addCommandButton("saveContactInformation", $lng->txt("save")); - - $this->form->setTitle($lng->txt("contact_data")); - $this->form->setFormAction($this->ctrl->getFormAction($this)); - - } - - /** - * Save contact information form - * - */ - public function saveContactInformationObject() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilSetting = $this->settings; - $rbacsystem = $this->rbacsystem; - $ilErr = $this->error; - - if (!$rbacsystem->checkAccess("write",$this->object->getRefId())) - { - $ilErr->raiseError($this->lng->txt("permission_denied"),$ilErr->MESSAGE); - } - - $this->initContactInformationForm(); - if ($this->form->checkInput()) - { - $fs = array("admin_firstname", "admin_lastname", "admin_title", "admin_position", - "admin_institution", "admin_street", "admin_zipcode", "admin_city", - "admin_country", "admin_phone", "admin_email"); - foreach ($fs as $f) - { - $ilSetting->set($f, $_POST[$f]); - } - - include_once("./Modules/SystemFolder/classes/class.ilSystemSupportContacts.php"); - ilSystemSupportContacts::setList($_POST["adm_support_contacts"]); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "showContactInformation"); - } - else - { - $this->setGeneralSettingsSubTabs("contact_data"); - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - } - - // - // - // Web Services - // - // - - /** - * Show Web Services - */ - function showWebServicesObject() - { - $tpl = $this->tpl; - - $this->initWebServicesForm(); - $this->setServerInfoSubTabs("webservices"); - $tpl->setContent($this->form->getHTML()); - } - - /** - * Init web services form. - */ - public function initWebServicesForm() - { - $lng = $this->lng; - $ilSetting = $this->settings; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // soap administration - $cb = new ilCheckboxInputGUI($this->lng->txt("soap_user_administration"), "soap_user_administration"); - $cb->setInfo($this->lng->txt("soap_user_administration_desc")); - if ($ilSetting->get("soap_user_administration")) - { - $cb->setChecked(true); - } - $this->form->addItem($cb); - - // wsdl path - $wsdl = new ilTextInputGUI($this->lng->txt('soap_wsdl_path'), 'soap_wsdl_path'); - $wsdl->setInfo(sprintf($this->lng->txt('soap_wsdl_path_info'), "
' . implode("", $scan_log) . ''; + $this->tpl->setVariable("ADM_CONTENT", $scan_log); + } else { + $scan_log = "no scanlog found."; + } + + // output + $this->tpl->addBlockFile( + "ADM_CONTENT", + "adm_content", + "tpl.adm_scan.html", + "Modules/SystemFolder" + ); + $this->tpl->setVariable("TXT_TITLE", $this->lng->txt("scan_details")); + $this->tpl->setVariable("COLSPAN", 3); + $this->tpl->setVariable("TXT_SCAN_LOG", $scan_log); + $this->tpl->setVariable("TXT_DONE", $this->lng->txt("done")); + } + + + /** + * Benchmark settings + */ + public function benchmarkObject() + { + $rbacsystem = $this->rbacsystem; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + $tpl = $this->tpl; + $ilErr = $this->error; + + if (!$rbacsystem->checkAccess("visible,read", $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); + } + + $this->benchmarkSubTabs("settings"); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // Activate DB Benchmark + $cb = new ilCheckboxInputGUI($lng->txt("adm_activate_db_benchmark"), "enable_db_bench"); + $cb->setChecked($ilSetting->get("enable_db_bench")); + $cb->setInfo($lng->txt("adm_activate_db_benchmark_desc")); + $this->form->addItem($cb); + + // DB Benchmark User + $ti = new ilTextInputGUI($lng->txt("adm_db_benchmark_user"), "db_bench_user"); + $ti->setValue($ilSetting->get("db_bench_user")); + $ti->setInfo($lng->txt("adm_db_benchmark_user_desc")); + $this->form->addItem($ti); + + $this->form->addCommandButton("saveBenchSettings", $lng->txt("save")); + + $this->form->setTitle($lng->txt("adm_db_benchmark")); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + + $tpl->setContent($this->form->getHTML()); + } + + /** + * Show db benchmark results + */ + public function showDbBenchChronologicalObject() + { + $this->benchmarkSubTabs("chronological"); + $this->showDbBenchResults("chronological"); + } + + /** + * Show db benchmark results + */ + public function showDbBenchSlowestFirstObject() + { + $this->benchmarkSubTabs("slowest_first"); + $this->showDbBenchResults("slowest_first"); + } + + /** + * Show db benchmark results + */ + public function showDbBenchSortedBySqlObject() + { + $this->benchmarkSubTabs("sorted_by_sql"); + $this->showDbBenchResults("sorted_by_sql"); + } + + /** + * Show db benchmark results + */ + public function showDbBenchByFirstTableObject() + { + $this->benchmarkSubTabs("by_first_table"); + $this->showDbBenchResults("by_first_table"); + } + + /** + * Show Db Benchmark Results + * + * @param string mode + */ + public function showDbBenchResults($a_mode) + { + $tpl = $this->tpl; + + $ilBench = $this->bench; + $rec = $ilBench->getDbBenchRecords(); + + include_once("./Modules/SystemFolder/classes/class.ilBenchmarkTableGUI.php"); + $table = new ilBenchmarkTableGUI($this, "benchmark", $rec, $a_mode); + $tpl->setContent($table->getHTML()); + } + + /** + * Benchmark sub tabs + * + * @param + * @return + */ + public function benchmarkSubTabs($a_current) + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilBench = $this->bench; + $ilTabs->activateTab("benchmarks"); // #18083 + + $ilTabs->addSubtab( + "settings", + $lng->txt("settings"), + $ilCtrl->getLinkTarget($this, "benchmark") + ); + + $rec = $ilBench->getDbBenchRecords(); + if (count($rec) > 0) { + $ilTabs->addSubtab( + "chronological", + $lng->txt("adm_db_bench_chronological"), + $ilCtrl->getLinkTarget($this, "showDbBenchChronological") + ); + $ilTabs->addSubtab( + "slowest_first", + $lng->txt("adm_db_bench_slowest_first"), + $ilCtrl->getLinkTarget($this, "showDbBenchSlowestFirst") + ); + $ilTabs->addSubtab( + "sorted_by_sql", + $lng->txt("adm_db_bench_sorted_by_sql"), + $ilCtrl->getLinkTarget($this, "showDbBenchSortedBySql") + ); + $ilTabs->addSubtab( + "by_first_table", + $lng->txt("adm_db_bench_by_first_table"), + $ilCtrl->getLinkTarget($this, "showDbBenchByFirstTable") + ); + } + + $ilTabs->activateSubTab($a_current); + } + + + /** + * Save benchmark settings + */ + public function saveBenchSettingsObject() + { + $ilBench = $this->bench; + if ($_POST["enable_db_bench"]) { + $ilBench->enableDbBench(true, ilUtil::stripSlashes($_POST["db_bench_user"])); + } else { + $ilBench->enableDbBench(false); + } + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + + $this->ctrl->redirect($this, "benchmark"); + } + + + /** + * save benchmark settings + */ + public function switchBenchModuleObject() + { + $this->ctrl->setParameter($this, 'cur_mod', $_POST['module']); + $this->ctrl->redirect($this, "benchmark"); + } + + + /** + * delete all benchmark records + */ + public function clearBenchObject() + { + $ilBench = $this->bench; + $ilBench->clearData(); + $this->saveBenchSettingsObject(); + } + + // get tabs + public function getAdminTabs() + { + $rbacsystem = $this->rbacsystem; + $ilHelp = $this->help; + + // $ilHelp->setScreenIdComponent($this->object->getType()); + + $this->ctrl->setParameter($this, "ref_id", $this->object->getRefId()); + + // general settings + if ($rbacsystem->checkAccess("write", $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "general_settings", + $this->ctrl->getLinkTarget($this, "showBasicSettings"), + array("showBasicSettings", "saveBasicSettings"), + get_class($this) + ); + } + + // server info + if ($rbacsystem->checkAccess("visible,read", $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "server", + $this->ctrl->getLinkTarget($this, "showServerInfo"), + array("showServerInfo", "view"), + get_class($this) + ); + } + + if ($rbacsystem->checkAccess("write", $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "cron_jobs", + $this->ctrl->getLinkTargetByClass("ilCronManagerGUI", ""), + "", + get_class($this) + ); + + // $tabs_gui->addTarget("system_check", + // $this->ctrl->getLinkTarget($this, "check"), array("check","viewScanLog","saveCheckParams","saveCheckCron"), get_class($this)); + + $this->tabs_gui->addTarget( + "benchmarks", + $this->ctrl->getLinkTarget($this, "benchmark"), + "benchmark", + get_class($this) + ); + } + + if ($rbacsystem->checkAccess('edit_permission', $this->object->getRefId())) { + $this->tabs_gui->addTarget( + "perm_settings", + $this->ctrl->getLinkTargetByClass(array(get_class($this),'ilpermissiongui'), "perm"), + array("perm","info","owner"), + 'ilpermissiongui' + ); + } + } + + /** + * Show PHP Information + */ + public function showPHPInfoObject() + { + phpinfo(); + exit; + } + + // + // + // Server Info + // + // + + /** + * Set sub tabs for server info + */ + public function setServerInfoSubTabs($a_activate) + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $rbacsystem = $this->rbacsystem; + + $ilTabs->addSubTabTarget("server_data", $ilCtrl->getLinkTarget($this, "showServerInfo")); + + if ($rbacsystem->checkAccess("write", $this->object->getRefId())) { + $ilTabs->addSubTabTarget("adm_https", $ilCtrl->getLinkTarget($this, "showHTTPS")); + $ilTabs->addSubTabTarget("proxy", $ilCtrl->getLinkTarget($this, "showProxy")); + $ilTabs->addSubTabTarget("java_server", $ilCtrl->getLinkTarget($this, "showJavaServer")); + $ilTabs->addSubTabTarget("webservices", $ilCtrl->getLinkTarget($this, "showWebServices")); + } + + $ilTabs->setSubTabActive($a_activate); + $ilTabs->setTabActive("server"); + } + + /** + * Show server info + */ + public function showServerInfoObject() + { + /** + * @var $ilToolbar ilToolbarGUI + * @var $lng ilLanguage + * @var $ilCtrl ilCtrl + * @var $tpl ilTemplate + */ + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $ilToolbar = $this->toolbar; + $lng = $this->lng; + + require_once 'Services/UIComponent/Button/classes/class.ilLinkButton.php'; + $button = ilLinkButton::getInstance(); + $button->setCaption('vc_information'); + $button->setUrl($this->ctrl->getLinkTarget($this, 'showVcsInformation')); + $ilToolbar->addButtonInstance($button); + + $this->initServerInfoForm(); + $this->setServerInfoSubTabs("server_data"); + + $btpl = new ilTemplate("tpl.server_data.html", true, true, "Modules/SystemFolder"); + $btpl->setVariable("FORM", $this->form->getHTML()); + $btpl->setVariable("PHP_INFO_TARGET", $ilCtrl->getLinkTarget($this, "showPHPInfo")); + $tpl->setContent($btpl->get()); + } + + /** + * Init server info form. + * + * @param int $a_mode Edit Mode + */ + public function initServerInfoForm() + { + $lng = $this->lng; + $ilClientIniFile = $this->client_ini; + $ilSetting = $this->settings; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // installation name + $ne = new ilNonEditableValueGUI($lng->txt("inst_name"), ""); + $ne->setValue($ilClientIniFile->readVariable("client", "name")); + $ne->setInfo($ilClientIniFile->readVariable("client", "description")); + $this->form->addItem($ne); + + // client id + $ne = new ilNonEditableValueGUI($lng->txt("client_id"), ""); + $ne->setValue(CLIENT_ID); + $this->form->addItem($ne); + + // installation id + $ne = new ilNonEditableValueGUI($lng->txt("inst_id"), ""); + $ne->setValue($ilSetting->get("inst_id")); + $this->form->addItem($ne); + + // database version + $ne = new ilNonEditableValueGUI($lng->txt("db_version"), ""); + $ne->setValue($ilSetting->get("db_version")); + + include_once("./Services/Database/classes/class.ilDBUpdate.php"); + $this->form->addItem($ne); + + // ilias version + $ne = new ilNonEditableValueGUI($lng->txt("ilias_version"), ""); + $ne->setValue($ilSetting->get("ilias_version")); + $this->form->addItem($ne); + + // host + $ne = new ilNonEditableValueGUI($lng->txt("host"), ""); + $ne->setValue($_SERVER["SERVER_NAME"]); + $this->form->addItem($ne); + + // ip & port + $ne = new ilNonEditableValueGUI($lng->txt("ip_address") . " & " . $this->lng->txt("port"), ""); + $ne->setValue($_SERVER["SERVER_ADDR"] . ":" . $_SERVER["SERVER_PORT"]); + $this->form->addItem($ne); + + // server + $ne = new ilNonEditableValueGUI($lng->txt("server_software"), ""); + $ne->setValue($_SERVER["SERVER_SOFTWARE"]); + $this->form->addItem($ne); + + // http path + $ne = new ilNonEditableValueGUI($lng->txt("http_path"), ""); + $ne->setValue(ILIAS_HTTP_PATH); + $this->form->addItem($ne); + + // absolute path + $ne = new ilNonEditableValueGUI($lng->txt("absolute_path"), ""); + $ne->setValue(ILIAS_ABSOLUTE_PATH); + $this->form->addItem($ne); + + $not_set = $lng->txt("path_not_set"); + + // convert + $ne = new ilNonEditableValueGUI($lng->txt("path_to_convert"), ""); + $ne->setValue((PATH_TO_CONVERT) ? PATH_TO_CONVERT : $not_set); + $this->form->addItem($ne); + + // zip + $ne = new ilNonEditableValueGUI($lng->txt("path_to_zip"), ""); + $ne->setValue((PATH_TO_ZIP) ? PATH_TO_ZIP : $not_set); + $this->form->addItem($ne); + + // unzip + $ne = new ilNonEditableValueGUI($lng->txt("path_to_unzip"), ""); + $ne->setValue((PATH_TO_UNZIP) ? PATH_TO_UNZIP : $not_set); + $this->form->addItem($ne); + + // java + $ne = new ilNonEditableValueGUI($lng->txt("path_to_java"), ""); + $ne->setValue((PATH_TO_JAVA) ? PATH_TO_JAVA : $not_set); + $this->form->addItem($ne); + + // mkisofs + $ne = new ilNonEditableValueGUI($lng->txt("path_to_mkisofs"), ""); + $ne->setValue((PATH_TO_MKISOFS) ? PATH_TO_MKISOFS : $not_set); + $this->form->addItem($ne); + + // latex + $ne = new ilNonEditableValueGUI($lng->txt("url_to_latex"), ""); + $ne->setValue((URL_TO_LATEX) ? URL_TO_LATEX : $not_set); + $this->form->addItem($ne); + + + $this->form->setTitle($lng->txt("server_data")); + $this->form->setFormAction($this->ctrl->getFormAction($this)); + } + + // + // + // General Settings + // + // + + /** + * Set sub tabs for general settings + */ + public function setGeneralSettingsSubTabs($a_activate) + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + + $ilTabs->addSubTabTarget("basic_settings", $ilCtrl->getLinkTarget($this, "showBasicSettings")); + $ilTabs->addSubTabTarget("header_title", $ilCtrl->getLinkTarget($this, "showHeaderTitle")); + $ilTabs->addSubTabTarget("contact_data", $ilCtrl->getLinkTarget($this, "showContactInformation")); + $ilTabs->addSubTabTarget("adm_imprint", $ilCtrl->getLinkTargetByClass("ilimprintgui", "preview")); + + $ilTabs->setSubTabActive($a_activate); + $ilTabs->setTabActive("general_settings"); + } + + // + // + // Basic Settings + // + // + + /** + * Show basic settings + */ + public function showBasicSettingsObject() + { + $tpl = $this->tpl; + + $this->initBasicSettingsForm(); + $this->setGeneralSettingsSubTabs("basic_settings"); + + $tpl->setContent($this->form->getHTML()); + } + + + /** + * Init basic settings form. + */ + public function initBasicSettingsForm() + { + /** + * @var $lng ilLanguage + * @var $ilSetting ilSetting + */ + $lng = $this->lng; + $ilSetting = $this->settings; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + $lng->loadLanguageModule("pd"); + + // installation short title + $ti = new ilTextInputGUI($this->lng->txt("short_inst_name"), "short_inst_name"); + $ti->setMaxLength(200); + $ti->setSize(40); + $ti->setValue($ilSetting->get("short_inst_name")); + $ti->setInfo($this->lng->txt("short_inst_name_info")); + $this->form->addItem($ti); + + + $cb = new ilCheckboxInputGUI($this->lng->txt("pub_section"), "pub_section"); + $cb->setInfo($lng->txt("pub_section_info")); + if (ilPublicSectionSettings::getInstance()->isEnabled()) { + $cb->setChecked(true); + } + $this->form->addItem($cb); + + $this->lng->loadLanguageModule('administration'); + $domains = new ilTextInputGUI($this->lng->txt('adm_pub_section_domain_filter'), 'public_section_domains'); + $domains->setInfo($this->lng->txt('adm_pub_section_domain_filter_info')); + $domains->setMulti(true); + $domains->setValue(current(ilPublicSectionSettings::getInstance()->getDomains())); + $domains->setMultiValues(ilPublicSectionSettings::getInstance()->getDomains()); + + $cb->addSubItem($domains); + + + // Enable Global Profiles + $cb_prop = new ilCheckboxInputGUI($lng->txt('pd_enable_user_publish'), 'enable_global_profiles'); + $cb_prop->setInfo($lng->txt('pd_enable_user_publish_info')); + $cb_prop->setChecked($ilSetting->get('enable_global_profiles')); + $cb->addSubItem($cb_prop); + + // search engine + include_once('Services/PrivacySecurity/classes/class.ilRobotSettings.php'); + $robot_settings = ilRobotSettings::_getInstance(); + $cb2 = new ilCheckboxInputGUI($this->lng->txt("search_engine"), "open_google"); + $cb2->setInfo($this->lng->txt("enable_search_engine")); + $this->form->addItem($cb2); + + if (!$robot_settings->checkRewrite()) { + $cb2->setAlert($lng->txt("allow_override_alert")); + $cb2->setChecked(false); + $cb2->setDisabled(true); + } else { + if ($ilSetting->get("open_google")) { + $cb2->setChecked(true); + } + } + + // locale + $ti = new ilTextInputGUI($this->lng->txt("adm_locale"), "locale"); + $ti->setMaxLength(80); + $ti->setSize(40); + $ti->setInfo($this->lng->txt("adm_locale_info")); + $ti->setValue($ilSetting->get("locale")); + $this->form->addItem($ti); + + // save and cancel commands + $this->form->addCommandButton("saveBasicSettings", $lng->txt("save")); + + $this->form->setTitle($lng->txt("basic_settings")); + $this->form->setFormAction($this->ctrl->getFormAction($this)); + } + + /** + * Save basic settings form + * + */ + public function saveBasicSettingsObject() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + + if (!$rbacsystem->checkAccess("write", $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); + } + + $this->initBasicSettingsForm(); + if ($this->form->checkInput()) { + $ilSetting->set("short_inst_name", $_POST["short_inst_name"]); + + $public_section = ilPublicSectionSettings::getInstance(); + $public_section->setEnabled($this->form->getInput('pub_section')); + + $domains = array(); + foreach ((array) $this->form->getInput('public_section_domains') as $domain) { + if (strlen(trim($domain))) { + $domains[] = $domain; + } + } + $public_section->setDomains($domains); + $public_section->save(); + + $global_profiles = ($_POST["pub_section"]) + ? (int) $_POST['enable_global_profiles'] + : 0; + $ilSetting->set('enable_global_profiles', $global_profiles); + + $ilSetting->set("open_google", $_POST["open_google"]); + $ilSetting->set("locale", $_POST["locale"]); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "showBasicSettings"); + } + $this->setGeneralSettingsSubTabs("basic_settings"); + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + + // + // + // Header title + // + // + + /** + * Show header title + */ + public function showHeaderTitleObject($a_get_post_values = false) + { + $tpl = $this->tpl; + + $this->setGeneralSettingsSubTabs("header_title"); + include_once("./Services/Object/classes/class.ilObjectTranslationTableGUI.php"); + $table = new ilObjectTranslationTableGUI($this, "showHeaderTitle", false); + if ($a_get_post_values) { + $vals = array(); + foreach ($_POST["title"] as $k => $v) { + $vals[] = array("title" => $v, + "desc" => $_POST["desc"][$k], + "lang" => $_POST["lang"][$k], + "default" => ($_POST["default"] == $k)); + } + $table->setData($vals); + } else { + $data = $this->object->getHeaderTitleTranslations(); + if (is_array($data["Fobject"])) { + foreach ($data["Fobject"] as $k => $v) { + if ($k == $data["default_language"]) { + $data["Fobject"][$k]["default"] = true; + } else { + $data["Fobject"][$k]["default"] = false; + } + } + } else { + $data["Fobject"] = array(); + } + $table->setData($data["Fobject"]); + } + $tpl->setContent($table->getHTML()); + } + + /** + * Save header titles + */ + public function saveHeaderTitlesObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + + if (!$rbacsystem->checkAccess("write", $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); + } + + // var_dump($_POST); + + // default language set? + if (!isset($_POST["default"]) && count($_POST["lang"]) > 0) { + ilUtil::sendFailure($lng->txt("msg_no_default_language")); + return $this->showHeaderTitleObject(true); + } + + // all languages set? + if (array_key_exists("", $_POST["lang"])) { + ilUtil::sendFailure($lng->txt("msg_no_language_selected")); + return $this->showHeaderTitleObject(true); + } + + // no single language is selected more than once? + if (count(array_unique($_POST["lang"])) < count($_POST["lang"])) { + ilUtil::sendFailure($lng->txt("msg_multi_language_selected")); + return $this->showHeaderTitleObject(true); + } + + // save the stuff + $this->object->removeHeaderTitleTranslations(); + foreach ($_POST["title"] as $k => $v) { + $this->object->addHeaderTitleTranslation( + ilUtil::stripSlashes($v), + ilUtil::stripSlashes($_POST["desc"][$k]), + ilUtil::stripSlashes($_POST["lang"][$k]), + ($_POST["default"] == $k) + ); + } + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "showHeaderTitle"); + } + + /** + * Add a header title + */ + public function addHeaderTitleObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (is_array($_POST["title"])) { + foreach ($_POST["title"] as $k => $v) { + } + } + $k++; + $_POST["title"][$k] = ""; + $this->showHeaderTitleObject(true); + } + + /** + * Remove header titles + */ + public function deleteHeaderTitlesObject() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + //var_dump($_POST); + foreach ($_POST["title"] as $k => $v) { + if ($_POST["check"][$k]) { + unset($_POST["title"][$k]); + unset($_POST["desc"][$k]); + unset($_POST["lang"][$k]); + if ($k == $_POST["default"]) { + unset($_POST["default"]); + } + } + } + $this->saveHeaderTitlesObject(); + } + + + // + // + // Cron Jobs + // + // + + /* + * OLD GLOBAL CRON JOB SWITCHES (ilSetting) + * + * cron_user_check => obsolete + * cron_inactive_user_delete => obsolete + * cron_inactivated_user_delete => obsolete + * cron_link_check => obsolete + * cron_web_resource_check => migrated + * cron_lucene_index => obsolete + * forum_notification => migrated + * mail_notification => migrated + * disk_quota/enabled => migrated + * crsgrp_ntf => migrated + * cron_upd_adrbook => migrated + */ + + public function jumpToCronJobsObject() + { + // #13010 - this is used for external settings + $this->ctrl->redirectByClass("ilCronManagerGUI", "render"); + } + + + // + // + // Contact Information + // + // + + /** + * Show contact information + */ + public function showContactInformationObject() + { + $tpl = $this->tpl; + + $this->initContactInformationForm(); + $this->setGeneralSettingsSubTabs("contact_data"); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Init contact information form. + */ + public function initContactInformationForm() + { + $lng = $this->lng; + $ilSetting = $this->settings; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // first name + $ti = new ilTextInputGUI($this->lng->txt("firstname"), "admin_firstname"); + $ti->setMaxLength(64); + $ti->setSize(40); + $ti->setRequired(true); + $ti->setValue($ilSetting->get("admin_firstname")); + $this->form->addItem($ti); + + // last name + $ti = new ilTextInputGUI($this->lng->txt("lastname"), "admin_lastname"); + $ti->setMaxLength(64); + $ti->setSize(40); + $ti->setRequired(true); + $ti->setValue($ilSetting->get("admin_lastname")); + $this->form->addItem($ti); + + // title + $ti = new ilTextInputGUI($this->lng->txt("title"), "admin_title"); + $ti->setMaxLength(64); + $ti->setSize(40); + $ti->setValue($ilSetting->get("admin_title")); + $this->form->addItem($ti); + + // position + $ti = new ilTextInputGUI($this->lng->txt("position"), "admin_position"); + $ti->setMaxLength(64); + $ti->setSize(40); + $ti->setValue($ilSetting->get("admin_position")); + $this->form->addItem($ti); + + // institution + $ti = new ilTextInputGUI($this->lng->txt("institution"), "admin_institution"); + $ti->setMaxLength(200); + $ti->setSize(40); + $ti->setValue($ilSetting->get("admin_institution")); + $this->form->addItem($ti); + + // street + $ti = new ilTextInputGUI($this->lng->txt("street"), "admin_street"); + $ti->setMaxLength(64); + $ti->setSize(40); + //$ti->setRequired(true); + $ti->setValue($ilSetting->get("admin_street")); + $this->form->addItem($ti); + + // zip code + $ti = new ilTextInputGUI($this->lng->txt("zipcode"), "admin_zipcode"); + $ti->setMaxLength(10); + $ti->setSize(5); + //$ti->setRequired(true); + $ti->setValue($ilSetting->get("admin_zipcode")); + $this->form->addItem($ti); + + // city + $ti = new ilTextInputGUI($this->lng->txt("city"), "admin_city"); + $ti->setMaxLength(64); + $ti->setSize(40); + //$ti->setRequired(true); + $ti->setValue($ilSetting->get("admin_city")); + $this->form->addItem($ti); + + // country + $ti = new ilTextInputGUI($this->lng->txt("country"), "admin_country"); + $ti->setMaxLength(64); + $ti->setSize(40); + //$ti->setRequired(true); + $ti->setValue($ilSetting->get("admin_country")); + $this->form->addItem($ti); + + // phone + $ti = new ilTextInputGUI($this->lng->txt("phone"), "admin_phone"); + $ti->setMaxLength(64); + $ti->setSize(40); + //$ti->setRequired(true); + $ti->setValue($ilSetting->get("admin_phone")); + $this->form->addItem($ti); + + // email + $ti = new ilEmailInputGUI($this->lng->txt("email"), "admin_email"); + $ti->setMaxLength(64); + $ti->setSize(40); + $ti->setRequired(true); + $ti->allowRFC822(true); + $ti->setValue($ilSetting->get("admin_email")); + $this->form->addItem($ti); + + // feedback recipient + /* currently used in: + - footer + - terms of service: no document found message + */ + /*$ti = new ilEmailInputGUI($this->lng->txt("feedback_recipient"), "feedback_recipient"); + $ti->setInfo(sprintf($this->lng->txt("feedback_recipient_info"), $this->lng->txt("contact_sysadmin"))); + $ti->setMaxLength(64); + $ti->setSize(40); + $ti->setRequired(true); + $ti->allowRFC822(true); + $ti->setValue($ilSetting->get("feedback_recipient")); + $this->form->addItem($ti);*/ + + // System support contacts + include_once("./Modules/SystemFolder/classes/class.ilSystemSupportContacts.php"); + $ti = new ilTextInputGUI($this->lng->txt("adm_support_contacts"), "adm_support_contacts"); + $ti->setMaxLength(500); + $ti->setValue(ilSystemSupportContacts::getList()); + //$ti->setSize(); + $ti->setInfo($this->lng->txt("adm_support_contacts_info")); + $this->form->addItem($ti); + + + // error recipient + /*$ti = new ilEmailInputGUI($this->lng->txt("error_recipient"), "error_recipient"); + $ti->setMaxLength(64); + $ti->setSize(40); + $ti->allowRFC822(true); + $ti->setValue($ilSetting->get("error_recipient")); + $this->form->addItem($ti);*/ + + $this->form->addCommandButton("saveContactInformation", $lng->txt("save")); + + $this->form->setTitle($lng->txt("contact_data")); + $this->form->setFormAction($this->ctrl->getFormAction($this)); + } + + /** + * Save contact information form + * + */ + public function saveContactInformationObject() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilSetting = $this->settings; + $rbacsystem = $this->rbacsystem; + $ilErr = $this->error; + + if (!$rbacsystem->checkAccess("write", $this->object->getRefId())) { + $ilErr->raiseError($this->lng->txt("permission_denied"), $ilErr->MESSAGE); + } + + $this->initContactInformationForm(); + if ($this->form->checkInput()) { + $fs = array("admin_firstname", "admin_lastname", "admin_title", "admin_position", + "admin_institution", "admin_street", "admin_zipcode", "admin_city", + "admin_country", "admin_phone", "admin_email"); + foreach ($fs as $f) { + $ilSetting->set($f, $_POST[$f]); + } + + include_once("./Modules/SystemFolder/classes/class.ilSystemSupportContacts.php"); + ilSystemSupportContacts::setList($_POST["adm_support_contacts"]); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "showContactInformation"); + } else { + $this->setGeneralSettingsSubTabs("contact_data"); + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + } + + // + // + // Web Services + // + // + + /** + * Show Web Services + */ + public function showWebServicesObject() + { + $tpl = $this->tpl; + + $this->initWebServicesForm(); + $this->setServerInfoSubTabs("webservices"); + $tpl->setContent($this->form->getHTML()); + } + + /** + * Init web services form. + */ + public function initWebServicesForm() + { + $lng = $this->lng; + $ilSetting = $this->settings; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // soap administration + $cb = new ilCheckboxInputGUI($this->lng->txt("soap_user_administration"), "soap_user_administration"); + $cb->setInfo($this->lng->txt("soap_user_administration_desc")); + if ($ilSetting->get("soap_user_administration")) { + $cb->setChecked(true); + } + $this->form->addItem($cb); + + // wsdl path + $wsdl = new ilTextInputGUI($this->lng->txt('soap_wsdl_path'), 'soap_wsdl_path'); + $wsdl->setInfo(sprintf($this->lng->txt('soap_wsdl_path_info'), "
" . $md . "
", $output); - } - } - - - return $output; - } - - /** - * All links to a specific page - */ - function whatLinksHere() - { - $tpl = $this->tpl; - - include_once("./Modules/Wiki/classes/class.ilWikiPagesTableGUI.php"); - - $this->setSideBlock($_GET["wpg_id"]); - $table_gui = new ilWikiPagesTableGUI($this, "whatLinksHere", - $this->getWikiPage()->getWikiId(), IL_WIKI_WHAT_LINKS_HERE, $_GET["wpg_id"]); - - $tpl->setContent($table_gui->getHTML()); - } - - function getTabs($a_activate = "") - { - $ilTabs = $this->tabs; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - - parent::getTabs($a_activate); - - if($ilAccess->checkAccess("statistics_read", "", $_GET["ref_id"])) - { - $ilTabs->addTarget("statistics", - $this->ctrl->getLinkTargetByClass(array("ilwikipagegui", "ilwikistatgui"), - "initial"), "", "ilwikistatgui"); - } - - $ilCtrl->setParameterByClass("ilobjwikigui", "wpg_id", - ilWikiPage::getPageIdForTitle($this->getPageObject()->getParentId(), - ilWikiUtil::makeDbTitle($_GET["page"]))); - $ilCtrl->setParameterByClass("ilobjwikigui", "page", ilWikiUtil::makeUrlTitle($_GET["page"])); - - $ilTabs->addTarget("wiki_what_links_here", - $this->ctrl->getLinkTargetByClass("ilwikipagegui", - "whatLinksHere"), "whatLinksHere"); - //$ilTabs->addTarget("wiki_print_view", - // $this->ctrl->getLinkTargetByClass("ilobjwikigui", - // "printViewSelection"), "printViewSelection"); - $ilTabs->addTarget("wiki_print_view", - $this->ctrl->getLinkTargetByClass("ilwikipagegui", - "printViewSelection"), "printViewSelection"); - - } - - /** - * Delete wiki page confirmation screen. - */ - function deleteWikiPageConfirmationScreen() - { - $ilAccess = $this->access; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Modules/Wiki/classes/class.ilWikiPerm.php"); - if (ilWikiPerm::check("delete_wiki_pages", $_GET["ref_id"])) - { - include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); - $confirmation_gui = new ilConfirmationGUI(); - $confirmation_gui->setFormAction($ilCtrl->getFormAction($this)); - $confirmation_gui->setHeaderText($lng->txt("wiki_page_deletion_confirmation")); - $confirmation_gui->setCancel($lng->txt("cancel"), "cancelWikiPageDeletion"); - $confirmation_gui->setConfirm($lng->txt("delete"), "confirmWikiPageDeletion"); - - $dtpl = new ilTemplate("tpl.wiki_page_deletion_confirmation.html", true, - true, "Modules/Wiki"); - - $dtpl->setVariable("PAGE_TITLE", $this->getWikiPage()->getTitle()); - - // other pages that link to this page - $dtpl->setVariable("TXT_OTHER_PAGES", $lng->txt("wiki_other_pages_linking")); - $pages = ilWikiPage::getLinksToPage($this->getWikiPage()->getWikiId(), - $this->getWikiPage()->getId()); - if (count($pages) > 0) - { - foreach($pages as $page) - { - $dtpl->setCurrentBlock("lpage"); - $dtpl->setVariable("TXT_LINKING_PAGE", $page["title"]); - $dtpl->parseCurrentBlock(); - } - } - else - { - $dtpl->setCurrentBlock("lpage"); - $dtpl->setVariable("TXT_LINKING_PAGE", "-"); - $dtpl->parseCurrentBlock(); - } - - // contributors - $dtpl->setVariable("TXT_CONTRIBUTORS", $lng->txt("wiki_contributors")); - $contributors = ilWikiPage::getWikiPageContributors($this->getWikiPage()->getId()); - foreach($contributors as $contributor) - { - $dtpl->setCurrentBlock("contributor"); - $dtpl->setVariable("TXT_CONTRIBUTOR", - $contributor["lastname"].", ".$contributor["firstname"]); - $dtpl->parseCurrentBlock(); - } - - // notes/comments - include_once("./Services/Notes/classes/class.ilNote.php"); - $cnt_note_users = ilNote::getUserCount($this->getPageObject()->getParentId(), - $this->getPageObject()->getId(), "wpg"); - $dtpl->setVariable("TXT_NUMBER_USERS_NOTES_OR_COMMENTS", - $lng->txt("wiki_number_users_notes_or_comments")); - $dtpl->setVariable("TXT_NR_NOTES_COMMENTS", $cnt_note_users); - - $confirmation_gui->addItem("", "", $dtpl->get()); - - $tpl->setContent($confirmation_gui->getHTML()); - } - } - - /** - * Cancel wiki page deletion - */ - function cancelWikiPageDeletion() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $ilCtrl->redirect($this, "preview"); - - } - - /** - * Delete the wiki page - */ - function confirmWikiPageDeletion() - { - $ilAccess = $this->access; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Modules/Wiki/classes/class.ilWikiPerm.php"); - if (ilWikiPerm::check("delete_wiki_pages", $_GET["ref_id"])) - { - $this->getPageObject()->delete(); - - ilUtil::sendSuccess($lng->txt("wiki_page_deleted"), true); - } - - $ilCtrl->redirectByClass("ilobjwikigui", "allPages"); - } - - //// - //// Print view selection - //// - - /** - * Print view selection - * - * @param - * @return - */ - function printViewSelection() - { - $ilUser = $this->user; - $lng = $this->lng; - $ilToolbar = $this->toolbar; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - - /*$ilToolbar->setFormAction($ilCtrl->getFormActionByClass("ilobjwikigui", "printView"), - false, "print_view"); - $ilToolbar->addFormButton($lng->txt("cont_show_print_view"), "printView"); - $ilToolbar->setCloseFormTag(false);*/ - - $this->initPrintViewSelectionForm(); - - $tpl->setContent($this->form->getHTML()); - } - - /** - * Init print view selection form. - */ - public function initPrintViewSelectionForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $pages = ilWikiPage::getAllWikiPages(ilObject::_lookupObjId($this->getWikiRefId())); - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // because of PDF export - $this->form->setPreventDoubleSubmission(false); - -//var_dump($pages); - // selection type - $radg = new ilRadioGroupInputGUI($lng->txt("cont_selection"), "sel_type"); - $radg->setValue("page"); - $op1 = new ilRadioOption($lng->txt("cont_current_page"), "page"); - $radg->addOption($op1); - $op2 = new ilRadioOption($lng->txt("wiki_whole_wiki") - ." (".$lng->txt("wiki_pages").": ".count($pages).")", "wiki"); - $radg->addOption($op2); - $op3= new ilRadioOption($lng->txt("wiki_selected_pages"), "selection"); - $radg->addOption($op3); - - include_once("./Services/Form/classes/class.ilNestedListInputGUI.php"); - $nl = new ilNestedListInputGUI("", "obj_id"); - $op3->addSubItem($nl); - - foreach ($pages as $p) - { - $nl->addListNode($p["id"], $p["title"], 0, false, false, - ilUtil::getImagePath("icon_pg.svg"), $lng->txt("wiki_page")); - } - - $this->form->addItem($radg); - - $this->form->addCommandButton("printViewOrder", $lng->txt("wiki_show_print_view")); - $this->form->addCommandButton("pdfExportOrder", $lng->txt("wiki_show_pdf_export")); - //$this->form->setOpenTag(false); - //$this->form->setCloseTag(false); - - $this->form->setTitle($lng->txt("cont_print_selection")); - $this->form->setFormAction($ilCtrl->getFormAction($this, "printViewOrder")); - } - - public function printViewOrder() - { - $this->printViewOrderList(); - } - - public function pdfExportOrder() - { - $this->printViewOrderList(true); - } - - protected function printViewOrderList($a_pdf_export = false) - { - $ilTabs = $this->tabs; - - $pg_ids = $all_pages = array(); - - // coming from type selection - if(!is_array($_POST["wordr"])) - { - switch(trim($_POST["sel_type"])) - { - case "wiki": - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $all_pages = ilWikiPage::getAllWikiPages($this->getPageObject()->getWikiId()); - foreach ($all_pages as $p) - { - $pg_ids[] = $p["id"]; - } - break; - - case "selection": - if (is_array($_POST["obj_id"])) - { - $pg_ids = $_POST["obj_id"]; - } - else - { - $pg_ids[] = $_GET["wpg_id"]; - } - if(sizeof($pg_ids) > 1) - { - break; - } - else - { - $_GET["wpg_id"] = array_pop($pg_ids); - } - // fallthrough - - // no order needed for single page - default: - //case "page": - $this->ctrl->setParameterByClass("ilObjWikiGUI", "wpg_id", $_GET["wpg_id"]); - if($a_pdf_export) - { - $this->ctrl->redirectByClass("ilObjWikiGUI", "pdfExport"); - } - else - { - $this->ctrl->redirectByClass("ilObjWikiGUI", "printView"); - } - break; - } - - if($a_pdf_export) - { - $this->ctrl->setParameter($this, "pexp", 1); - } - } - // refresh sorting - else - { - $a_pdf_export = (bool)$_GET["pexp"]; - - asort($_POST["wordr"]); - $pg_ids = array_keys($_POST["wordr"]); - } - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($this->lng->txt("back"), - $this->ctrl->getLinkTarget($this, "preview")); - - if(!sizeof($all_pages)) - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $all_pages = ilWikiPage::getAllWikiPages($this->getPageObject()->getWikiId()); - } - - include_once "Modules/Wiki/classes/class.ilWikiExportOrderTableGUI.php"; - $tbl = new ilWikiExportOrderTableGUI($this, "printViewOrderList", $a_pdf_export, $all_pages, $pg_ids); - $this->tpl->setContent($tbl->getHTML()); - } - - - //// - //// Block/Unblock - //// - - /** - * Block - */ - function blockWikiPage() - { - $ilAccess = $this->access; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Modules/Wiki/classes/class.ilWikiPerm.php"); - if (ilWikiPerm::check("activate_wiki_protection", $_GET["ref_id"])) - { - $this->getPageObject()->setBlocked(true); - $this->getPageObject()->update(); - - ilUtil::sendSuccess($lng->txt("wiki_page_blocked"), true); - } - - $ilCtrl->redirect($this, "preview"); - } - - /** - * Unblock - */ - function unblockWikiPage() - { - $ilAccess = $this->access; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Modules/Wiki/classes/class.ilWikiPerm.php"); - if (ilWikiPerm::check("activate_wiki_protection", $_GET["ref_id"])) - { - $this->getPageObject()->setBlocked(false); - $this->getPageObject()->update(); - - ilUtil::sendSuccess($lng->txt("wiki_page_unblocked"), true); - } - - $ilCtrl->redirect($this, "preview"); - } - - - //// - //// Rename - //// - - /** - * Rename wiki page form - */ - function renameWikiPage() - { - $ilAccess = $this->access; - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (($ilAccess->checkAccess("edit_content", "", $_GET["ref_id"]) && !$this->getPageObject()->getBlocked()) - || $ilAccess->checkAccess("write", "", $_GET["ref_id"])) - { - $this->initRenameForm(); - $tpl->setContent($this->form->getHTML()); - } - } - - /** - * Init renaming form. - * - * @param int $a_mode Edit Mode - */ - protected function initRenameForm() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $this->form = new ilPropertyFormGUI(); - - // new name - $ti = new ilTextInputGUI($lng->txt("wiki_new_page_name"), "new_page_name"); - $ti->setMaxLength(200); - $ti->setSize(50); - $ti->setValue($this->getPageObject()->getTitle()); - $ti->setRequired(true); - $this->form->addItem($ti); - - $this->form->addCommandButton("renamePage", $lng->txt("wiki_rename")); - $this->form->addCommandButton("preview", $lng->txt("cancel")); - - $this->form->setTitle($lng->txt("wiki_rename_page")); - $this->form->setFormAction($ilCtrl->getFormAction($this)); - } - - /** - * Rename page - */ - public function renamePage() - { - $tpl = $this->tpl; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - - $this->initRenameForm(); - if ($this->form->checkInput()) - { - if (($ilAccess->checkAccess("edit_content", "", $_GET["ref_id"]) && !$this->getPageObject()->getBlocked()) - || $ilAccess->checkAccess("write", "", $_GET["ref_id"])) - { - $new_name = $this->form->getInput("new_page_name"); - - $page_title = ilWikiUtil::makeDbTitle($new_name); - $pg_id = ilWikiPage::_getPageIdForWikiTitle($this->getPageObject()->getWikiId(), $page_title); - - // we might get the same page id back here, if the page - // name only differs in diacritics - // see bug http://www.ilias.de/mantis/view.php?id=11226 - if ($pg_id > 0 && $pg_id != $this->getPageObject()->getId()) - { - ilUtil::sendFailure($lng->txt("wiki_page_already_exists")); - } - else - { - $new_name = $this->getPageObject()->rename($new_name); - $ilCtrl->setParameterByClass("ilobjwikigui", "page", ilWikiUtil::makeUrlTitle($new_name)); - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "preview"); - } - } - } - - $this->form->setValuesByPost(); - $tpl->setContent($this->form->getHtml()); - } - - //// - /// Rating - //// - - function activateWikiPageRating() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->getPageObject()->setRating(true); - $this->getPageObject()->update(); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "preview"); - } - - function deactivateWikiPageRating() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $this->getPageObject()->setRating(false); - $this->getPageObject()->update(); - - ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); - $ilCtrl->redirect($this, "preview"); - } - - - function observeNoteAction($a_wiki_id, $a_page_id, $a_type, $a_action, $a_note_id) - { - // #10040 - get note text - include_once "Services/Notes/classes/class.ilNote.php"; - $note = new ilNote($a_note_id); - $note = $note->getText(); - - include_once "./Services/Notification/classes/class.ilNotification.php"; - ilWikiUtil::sendNotification("comment", ilNotification::TYPE_WIKI_PAGE, $this->getWikiRefId(), $a_page_id, $note); - } - - public function updateStatsRating($a_wiki_id, $a_wiki_type, $a_page_id, $a_page_type) - { - include_once "./Modules/Wiki/classes/class.ilWikiStat.php"; - ilWikiStat::handleEvent(ilWikiStat::EVENT_PAGE_RATING, $this->getPageObject()); - } - - - // - // advanced meta data - // - - protected function initAdvancedMetaDataForm() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - $page = $this->getWikiPage(); - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this, "updateAdvancedMetaData")); - - // :TODO: - $form->setTitle($lng->txt("wiki_advmd_block_title").": ".$page->getTitle()); - - include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); - $this->record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_EDITOR,'wiki',$page->getWikiId(),'wpg',$page->getId()); - $this->record_gui->setPropertyForm($form); - $this->record_gui->parse(); - - $form->addCommandButton("updateAdvancedMetaData", $lng->txt("save")); - $form->addCommandButton("preview", $lng->txt("cancel")); - - return $form; - } - - function editAdvancedMetaData(ilPropertyFormGUI $a_form = null) - { - $ilTabs = $this->tabs; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - $tpl = $this->tpl; - $ilAccess = $this->access; - - if (!$ilAccess->checkAccess("write", "", $this->wiki_ref_id) && - !$ilAccess->checkAccess("edit_page_meta", "", $this->wiki_ref_id)) - { - return; - } - - - $ilTabs->clearTargets(); - $ilTabs->setBackTarget($lng->txt("back"), - $ilCtrl->getLinkTarget($this, "preview")); - - if(!$a_form) - { - $a_form = $this->initAdvancedMetaDataForm(); - } - - $tpl->setContent($a_form->getHTML()); - } - - function updateAdvancedMetaData() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilAccess = $this->access; - - if (!$ilAccess->checkAccess("write", "", $this->wiki_ref_id) && - !$ilAccess->checkAccess("edit_page_meta", "", $this->wiki_ref_id)) - { - return; - } - - $form = $this->initAdvancedMetaDataForm(); - - // needed for proper advanced MD validation - $form->checkInput(); - if(!$this->record_gui->importEditFormPostValues()) - { - $this->editAdvancedMetaData($form); // #16470 - return false; - } - - if($this->record_gui->writeEditForm()) - { - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - } - $ilCtrl->redirect($this, "preview"); - } - - function hideAdvancedMetaData() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilAccess = $this->access; - - if (!$ilAccess->checkAccess("write", "", $this->wiki_ref_id) && - !$ilAccess->checkAccess("edit_page_meta", "", $this->wiki_ref_id)) - { - return; - } - - $this->getPageObject()->hideAdvancedMetadata(true); - $this->getPageObject()->update(); - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "preview"); - } - - function unhideAdvancedMetaData() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilAccess = $this->access; - - if (!$ilAccess->checkAccess("write", "", $this->wiki_ref_id) && - !$ilAccess->checkAccess("edit_page_meta", "", $this->wiki_ref_id)) - { - return; - } - - $this->getPageObject()->hideAdvancedMetadata(false); - $this->getPageObject()->update(); - - ilUtil::sendSuccess($lng->txt("settings_saved"), true); - $ilCtrl->redirect($this, "preview"); - } - - /** - * Edit - * - * @param - * @return - */ - function edit() - { - $tpl = $this->tpl; - $lng = $this->lng; - - self::initEditingJS($tpl); - - return parent::edit(); - } - - /** - * Init wiki editing js - * - * @param ilTemplate $a_tpl template - */ - static function initEditingJS(ilTemplate $a_tpl) - { - global $DIC; - - $lng = $DIC->language(); - - $a_tpl->addJavascript("./Modules/Wiki/js/WikiEdit.js"); - $a_tpl->addOnLoadCode("il.Wiki.Edit.txt.page_exists = '".$lng->txt("wiki_page_exists")."';"); - $a_tpl->addOnLoadCode("il.Wiki.Edit.txt.new_page = '".$lng->txt("wiki_new_page")."';"); - } - - - /** - * Returns form to insert a wiki link per ajax - */ - function insertWikiLink() - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->addCommandButton("addWikiLink", $lng->txt("wiki_add_link")); - $form->addCommandButton("searchWikiLink", $lng->txt("search")); - - // Target page - $tp = new ilTextInputGUI($this->lng->txt("wiki_target_page"), "target_page"); - $tp->setSize(18); - $tp->setRequired(true); - $tp->setInfo("..."); - $tp->setDataSource($ilCtrl->getLinkTarget($this, "insertWikiLinkAC", "", true)); - $form->addItem($tp); - - // Link text - $lt = new ilTextInputGUI($this->lng->txt("wiki_link_text"), "link_text"); - $lt->setSize(18); - $form->addItem($lt); - - //$form->setTitle($lng->txt("wiki_link")); - - echo $form->getHTML(); - exit; - } - - /** - * Auto complete for insert wiki link - */ - function insertWikiLinkAC() - { - $result = array(); - - $term = $_GET["term"]; - - // if page exists, make it first entry - if (ilWikiPage::_wikiPageExists($this->getPageObject()->getParentId(), $term)) - { - $entry = new stdClass(); - $entry->value = $term; - $entry->label = $term; - $result[] = $entry; - } - - $res = ilWikiPage::getPagesForSearch($this->getPageObject()->getParentId(), $term); - - $cnt = 0; - foreach ($res as $r) - { - if ($result[0]->value == $r) - { - continue; - } - if ($cnt++ > 19) - { - continue; - } - $entry = new stdClass(); - $entry->value = $r; - $entry->label = $r; - $result[] = $entry; - } - - include_once './Services/JSON/classes/class.ilJsonUtil.php'; - echo ilJsonUtil::encode($result); - exit; - } - - /** - * Search wiki link list - */ - function searchWikiLinkAC() - { - $lng = $this->lng; - - $lng->loadLanguageModule("wiki"); - - $tpl = new ilTemplate("tpl.wiki_ac_search_result.html", true, true, "Modules/Wiki"); - $term = trim($_GET["term"]); - - $pages = ilObjWiki::_performSearch($this->getPageObject()->getParentId(), $term); - - $found = array(); - foreach ($pages as $page) - { - $found[] = array("page_id" => $page["page_id"], "title" => ilWikiPage::lookupTitle($page["page_id"])); - } - - // sort if all pages are listed - if ($term == "") - { - $found = ilUtil::sortArray($found, "title", "asc"); - } - - foreach ($found as $f) - { - $tpl->setCurrentBlock("item"); - $tpl->setVariable("WIKI_TITLE", $f["title"]); - $tpl->parseCurrentBlock(); - } - - if (count($pages) == 0) - { - $tpl->setVariable("INFOTEXT", str_replace("$1", $term, $lng->txt("wiki_no_page_found"))); - } - else if ($term == '') - { - $tpl->setVariable("INFOTEXT", $lng->txt("wiki_no_search_term"), $term); - } - else - { - $tpl->setVariable("INFOTEXT", str_replace("$1", $term, $lng->txt("wiki_pages_found"))); - } - - $tpl->setVariable("TXT_BACK", $lng->txt("back")); - echo $tpl->get(); - exit; - } - - // - // exercise assignment - // - - /** - * Finalize and submit blog to exercise - */ - protected function finalizeAssignment() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php"); - include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); - $wiki_ass = ilExAssignmentTypes::getInstance()->getById(ilExAssignment::TYPE_WIKI_TEAM); - - $ass_id = (int) $_GET["ass"]; - $wiki_ass->submitWiki($ass_id, $this->user->getId(), $this->getWikiRefId()); - - /* - include_once "Modules/Exercise/classes/class.ilExSubmissionBaseGUI.php"; - include_once "Modules/Exercise/classes/class.ilExSubmissionObjectGUI.php"; - $exc_gui = ilExSubmissionObjectGUI::initGUIForSubmit($this->ass_id); - $exc_gui->submitBlog($this->node_id);*/ - - ilUtil::sendSuccess($lng->txt("wiki_finalized"), true); - $ilCtrl->redirect($this, "preview"); - } - - protected function downloadExcSubFile() - { - $ilUser = $this->user; - - $ass_id = (int) $_GET["ass"]; - $ass = new ilExAssignment($ass_id); - $submission = new ilExSubmission($ass, $ilUser->getId()); - $submitted = $submission->getFiles(); - if (count($submitted) > 0) - { - $submitted = array_pop($submitted); - - $user_data = ilObjUser::_lookupName($submitted["user_id"]); - $title = ilObject::_lookupTitle($submitted["obj_id"])." - ". - $ass->getTitle()." (Team ".$submission->getTeam()->getId().").zip"; - - ilUtil::deliverFile($submitted["filename"], $title); - } - } - - -} - -?> \ No newline at end of file + $this->wiki_ref_id = $a_ref_id; + } + + public function getWikiRefId() + { + return $this->wiki_ref_id; + } + + /** + * Set wiki + * + * @param ilObjWiki $a_val wiki + */ + public function setWiki($a_val) + { + $this->wiki = $a_val; + } + + /** + * Get wiki + * + * @return ilObjWiki wiki + */ + public function getWiki() + { + return $this->wiki; + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + $ilTabs = $this->tabs; + $ilUser = $this->user; + $ilAccess = $this->access; + $lng = $this->lng; + $tpl = $this->tpl; + + $next_class = $this->ctrl->getNextClass($this); + $cmd = $this->ctrl->getCmd(); + + $head_title = ilObject::_lookupTitle(ilObject::_lookupObjId((int) $_GET["ref_id"])) . ": " . $this->getWikiPage()->getTitle(); + $tpl->setHeaderPageTitle($head_title); + // see #13804 + if ($_GET["page"] != "") { + $tpl->setPermanentLink("wiki", "", "wpage_" . $this->getPageObject()->getId() . "_" . $_GET["ref_id"], "", $head_title); + } else { + $tpl->setPermanentLink("wiki", $_GET["ref_id"]); + } + + + switch ($next_class) { + case "ilnotegui": + $this->getTabs(); + $ilTabs->setTabActive("pg"); + return $this->preview(); + break; + + case "ilratinggui": + // for rating side block + include_once("./Services/Rating/classes/class.ilRatingGUI.php"); + $rating_gui = new ilRatingGUI(); + $rating_gui->setObject( + $this->getPageObject()->getParentId(), + "wiki", + $this->getPageObject()->getId(), + "wpg" + ); + $rating_gui->setUpdateCallback(array($this, "updateStatsRating")); + $this->ctrl->forwardCommand($rating_gui); + $ilCtrl->redirect($this, "preview"); + break; + + case "ilcommonactiondispatchergui": + include_once("Services/Object/classes/class.ilCommonActionDispatcherGUI.php"); + $gui = ilCommonActionDispatcherGUI::getInstanceFromAjaxCall(); + $gui->enableCommentsSettings(false); + $gui->setRatingCallback($this, "preview"); + $this->ctrl->forwardCommand($gui); + break; + + case "ilwikistatgui": + if ($ilAccess->checkAccess("statistics_read", "", $this->wiki_ref_id)) { + $this->tabs_gui->clearTargets(); // see ilObjWikiGUI::getTabs() + $this->getTabs("statistics"); + + include_once "Modules/Wiki/classes/class.ilWikiStatGUI.php"; + $gui = new ilWikiStatGUI( + $this->getPageObject()->getParentId(), + $this->getPageObject()->getId() + ); + $this->ctrl->forwardCommand($gui); + } + break; + case 'ilobjectmetadatagui': + + if (!$ilAccess->checkAccess("write", "", $this->wiki_ref_id)) { + ilUtil::sendFailure($lng->txt("permission_denied"), true); + $ilCtrl->redirect($this, "preview"); + } + return parent::executeCommand(); + break; + + case "ilpropertyformgui": + // only case is currently adv metadata internal link in info settings, see #24497 + $form = $this->initAdvancedMetaDataForm(); + $ilCtrl->forwardCommand($form); + break; + + default: + + if (strtolower($ilCtrl->getNextClass()) == "ilpageeditorgui") { + self::initEditingJS($this->tpl); + } + + if ($_GET["ntf"]) { + include_once "./Services/Notification/classes/class.ilNotification.php"; + switch ($_GET["ntf"]) { + case 1: + ilNotification::setNotification(ilNotification::TYPE_WIKI, $ilUser->getId(), $this->getPageObject()->getParentId(), false); + break; + + case 2: + // remove all page notifications here? + ilNotification::setNotification(ilNotification::TYPE_WIKI, $ilUser->getId(), $this->getPageObject()->getParentId(), true); + break; + + case 3: + ilNotification::setNotification(ilNotification::TYPE_WIKI_PAGE, $ilUser->getId(), $this->getPageObject()->getId(), false); + break; + + case 4: + ilNotification::setNotification(ilNotification::TYPE_WIKI_PAGE, $ilUser->getId(), $this->getPageObject()->getId(), true); + break; + } + $ilCtrl->redirect($this, "preview"); + } + + $this->setPresentationTitle($this->getWikiPage()->getTitle()); + return parent::executeCommand(); + } + } + + /** + * Set Wiki Page Object. + * + * @param object $a_wikipage Wiki Page Object + */ + public function setWikiPage($a_wikipage) + { + $this->setPageObject($a_wikipage); + } + + /** + * Get Wiki Page Object. + * + * @return object Wiki Page Object + */ + public function getWikiPage() + { + return $this->getPageObject(); + } + + /** + * Get wiki page gui for id and title + */ + public static function getGUIForTitle($a_wiki_id, $a_title, $a_old_nr = 0, $a_wiki_ref_id = 0) + { + global $DIC; + + $ilDB = $DIC->database(); + + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $id = ilWikiPage::getPageIdForTitle($a_wiki_id, $a_title); + $page_gui = new ilWikiPageGUI($id, $a_old_nr, $a_wiki_ref_id); + + return $page_gui; + } + + public function setSideBlock() + { + ilObjWikiGUI::renderSideBlock( + $this->getWikiPage()->getId(), + $this->wiki_ref_id, + $this->getWikiPage() + ); + } + + public function addHeaderAction($a_redraw = false) + { + $ilUser = $this->user; + $ilAccess = $this->access; + + $wiki_id = $this->getPageObject()->getParentId(); + $page_id = $this->getPageObject()->getId(); + + include_once "Services/Object/classes/class.ilCommonActionDispatcherGUI.php"; + $dispatcher = new ilCommonActionDispatcherGUI( + ilCommonActionDispatcherGUI::TYPE_REPOSITORY, + $ilAccess, + "wiki", + $_GET["ref_id"], + $wiki_id + ); + $dispatcher->setSubObject("wpg", $page_id); + + include_once "Services/Object/classes/class.ilObjectListGUI.php"; + ilObjectListGUI::prepareJSLinks( + $this->ctrl->getLinkTarget($this, "redrawHeaderAction", "", true), + $this->ctrl->getLinkTargetByClass(array("ilcommonactiondispatchergui", "ilnotegui"), "", "", true, false), + $this->ctrl->getLinkTargetByClass(array("ilcommonactiondispatchergui", "iltagginggui"), "", "", true, false) + ); + + $lg = $dispatcher->initHeaderAction(); + $lg->enableNotes(true); + $lg->enableComments(ilObjWiki::_lookupPublicNotes($wiki_id), false); + + // rating + if (ilObjWiki::_lookupRatingOverall($wiki_id)) { + $lg->enableRating( + true, + $this->lng->txt("wiki_rate_overall"), + false, + // so ilCtrl does not use the shortcut via ilWikiGUI + array("ilcommonactiondispatchergui", "ilratinggui") + ); + } + + // notification + if ($ilUser->getId() != ANONYMOUS_USER_ID) { + include_once "./Services/Notification/classes/class.ilNotification.php"; + if (ilNotification::hasNotification(ilNotification::TYPE_WIKI, $ilUser->getId(), $wiki_id)) { + $this->ctrl->setParameter($this, "ntf", 1); + if (ilNotification::hasOptOut($wiki_id)) { + $lg->addCustomCommand($this->ctrl->getLinkTarget($this), "wiki_notification_deactivate_wiki"); + } + + $lg->addHeaderIcon( + "not_icon", + ilUtil::getImagePath("notification_on.svg"), + $this->lng->txt("wiki_notification_activated") + ); + } else { + $this->ctrl->setParameter($this, "ntf", 2); + $lg->addCustomCommand($this->ctrl->getLinkTarget($this), "wiki_notification_activate_wiki"); + + if (ilNotification::hasNotification(ilNotification::TYPE_WIKI_PAGE, $ilUser->getId(), $page_id)) { + $this->ctrl->setParameter($this, "ntf", 3); + $lg->addCustomCommand($this->ctrl->getLinkTarget($this), "wiki_notification_deactivate_page"); + + $lg->addHeaderIcon( + "not_icon", + ilUtil::getImagePath("notification_on.svg"), + $this->lng->txt("wiki_page_notification_activated") + ); + } else { + $this->ctrl->setParameter($this, "ntf", 4); + $lg->addCustomCommand($this->ctrl->getLinkTarget($this), "wiki_notification_activate_page"); + + $lg->addHeaderIcon( + "not_icon", + ilUtil::getImagePath("notification_off.svg"), + $this->lng->txt("wiki_notification_deactivated") + ); + } + } + $this->ctrl->setParameter($this, "ntf", ""); + } + + if (!$a_redraw) { + $this->tpl->setHeaderActionMenu($lg->getHeaderAction()); + } else { + // we need to add onload code manually (rating, comments, etc.) + return $lg->getHeaderAction() . + $this->tpl->getOnLoadCodeForAsynch(); + } + } + + public function redrawHeaderAction() + { + echo $this->addHeaderAction(true); + exit; + } + + /** + * View wiki page. + */ + public function preview() + { + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $lng = $this->lng; + $tpl = $this->tpl; + $ilUser = $this->user; + $ilSetting = $this->settings; + $ui = $this->ui; + + + // block/unblock + if ($this->getPageObject()->getBlocked()) { + ilUtil::sendInfo($lng->txt("wiki_page_status_blocked")); + } + + // exercise information + include_once("./Modules/Exercise/RepoObjectAssignment/classes/class.ilExcRepoObjAssignment.php"); + $ass_info = ilExcRepoObjAssignment::getInstance()->getAssignmentInfoOfObj($this->getWikiRefId(), $ilUser->getId()); + $message = ""; + foreach ($ass_info as $i) { // should be only one + $links = $buttons = []; + $ass = new ilExAssignment($i->getId()); + $times_up = $ass->afterDeadlineStrict(); + + // info text and link + $exc_title = $i->getExerciseTitle(); + $info = sprintf( + $lng->txt("wiki_exercise_info"), + $i->getTitle(), + $exc_title + ); + foreach ($i->getLinks() as $l) { + $links[] = $ui->factory()->link()->standard($exc_title, $l); + } + + // submit button + if (!$times_up) { + $ilCtrl->setParameterByClass("ilwikipagegui", "ass", $ass->getId()); + $submit_link = $ilCtrl->getLinkTargetByClass("ilwikipagegui", "finalizeAssignment"); + $ilCtrl->setParameterByClass("ilwikipagegui", "ass", ""); + + $buttons[] = $ui->factory()->button()->primary($lng->txt("wiki_finalize_wiki"), $submit_link); + } + + // submitted files + include_once "Modules/Exercise/classes/class.ilExSubmission.php"; + $submission = new ilExSubmission($ass, $ilUser->getId()); + if ($submission->hasSubmitted()) { + $submitted = $submission->getSelectedObject(); + + $ilCtrl->setParameterByClass("ilwikipagegui", "ass", $ass->getId()); + $dl_link = $ilCtrl->getLinkTargetByClass("ilwikipagegui", "downloadExcSubFile"); + $ilCtrl->setParameterByClass("ilwikipagegui", "ass", ""); + + $rel = ilDatePresentation::useRelativeDates(); + ilDatePresentation::setUseRelativeDates(false); + + + $info .= "" . $md . "
", $output); + } + } + + + return $output; + } + + /** + * All links to a specific page + */ + public function whatLinksHere() + { + $tpl = $this->tpl; + + include_once("./Modules/Wiki/classes/class.ilWikiPagesTableGUI.php"); + + $this->setSideBlock($_GET["wpg_id"]); + $table_gui = new ilWikiPagesTableGUI( + $this, + "whatLinksHere", + $this->getWikiPage()->getWikiId(), + IL_WIKI_WHAT_LINKS_HERE, + $_GET["wpg_id"] + ); + + $tpl->setContent($table_gui->getHTML()); + } + + public function getTabs($a_activate = "") + { + $ilTabs = $this->tabs; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + + parent::getTabs($a_activate); + + if ($ilAccess->checkAccess("statistics_read", "", $_GET["ref_id"])) { + $ilTabs->addTarget( + "statistics", + $this->ctrl->getLinkTargetByClass( + array("ilwikipagegui", "ilwikistatgui"), + "initial" + ), + "", + "ilwikistatgui" + ); + } + + $ilCtrl->setParameterByClass( + "ilobjwikigui", + "wpg_id", + ilWikiPage::getPageIdForTitle( + $this->getPageObject()->getParentId(), + ilWikiUtil::makeDbTitle($_GET["page"]) + ) + ); + $ilCtrl->setParameterByClass("ilobjwikigui", "page", ilWikiUtil::makeUrlTitle($_GET["page"])); + + $ilTabs->addTarget( + "wiki_what_links_here", + $this->ctrl->getLinkTargetByClass( + "ilwikipagegui", + "whatLinksHere" + ), + "whatLinksHere" + ); + //$ilTabs->addTarget("wiki_print_view", + // $this->ctrl->getLinkTargetByClass("ilobjwikigui", + // "printViewSelection"), "printViewSelection"); + $ilTabs->addTarget( + "wiki_print_view", + $this->ctrl->getLinkTargetByClass( + "ilwikipagegui", + "printViewSelection" + ), + "printViewSelection" + ); + } + + /** + * Delete wiki page confirmation screen. + */ + public function deleteWikiPageConfirmationScreen() + { + $ilAccess = $this->access; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Modules/Wiki/classes/class.ilWikiPerm.php"); + if (ilWikiPerm::check("delete_wiki_pages", $_GET["ref_id"])) { + include_once("./Services/Utilities/classes/class.ilConfirmationGUI.php"); + $confirmation_gui = new ilConfirmationGUI(); + $confirmation_gui->setFormAction($ilCtrl->getFormAction($this)); + $confirmation_gui->setHeaderText($lng->txt("wiki_page_deletion_confirmation")); + $confirmation_gui->setCancel($lng->txt("cancel"), "cancelWikiPageDeletion"); + $confirmation_gui->setConfirm($lng->txt("delete"), "confirmWikiPageDeletion"); + + $dtpl = new ilTemplate( + "tpl.wiki_page_deletion_confirmation.html", + true, + true, + "Modules/Wiki" + ); + + $dtpl->setVariable("PAGE_TITLE", $this->getWikiPage()->getTitle()); + + // other pages that link to this page + $dtpl->setVariable("TXT_OTHER_PAGES", $lng->txt("wiki_other_pages_linking")); + $pages = ilWikiPage::getLinksToPage( + $this->getWikiPage()->getWikiId(), + $this->getWikiPage()->getId() + ); + if (count($pages) > 0) { + foreach ($pages as $page) { + $dtpl->setCurrentBlock("lpage"); + $dtpl->setVariable("TXT_LINKING_PAGE", $page["title"]); + $dtpl->parseCurrentBlock(); + } + } else { + $dtpl->setCurrentBlock("lpage"); + $dtpl->setVariable("TXT_LINKING_PAGE", "-"); + $dtpl->parseCurrentBlock(); + } + + // contributors + $dtpl->setVariable("TXT_CONTRIBUTORS", $lng->txt("wiki_contributors")); + $contributors = ilWikiPage::getWikiPageContributors($this->getWikiPage()->getId()); + foreach ($contributors as $contributor) { + $dtpl->setCurrentBlock("contributor"); + $dtpl->setVariable( + "TXT_CONTRIBUTOR", + $contributor["lastname"] . ", " . $contributor["firstname"] + ); + $dtpl->parseCurrentBlock(); + } + + // notes/comments + include_once("./Services/Notes/classes/class.ilNote.php"); + $cnt_note_users = ilNote::getUserCount( + $this->getPageObject()->getParentId(), + $this->getPageObject()->getId(), + "wpg" + ); + $dtpl->setVariable( + "TXT_NUMBER_USERS_NOTES_OR_COMMENTS", + $lng->txt("wiki_number_users_notes_or_comments") + ); + $dtpl->setVariable("TXT_NR_NOTES_COMMENTS", $cnt_note_users); + + $confirmation_gui->addItem("", "", $dtpl->get()); + + $tpl->setContent($confirmation_gui->getHTML()); + } + } + + /** + * Cancel wiki page deletion + */ + public function cancelWikiPageDeletion() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $ilCtrl->redirect($this, "preview"); + } + + /** + * Delete the wiki page + */ + public function confirmWikiPageDeletion() + { + $ilAccess = $this->access; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Modules/Wiki/classes/class.ilWikiPerm.php"); + if (ilWikiPerm::check("delete_wiki_pages", $_GET["ref_id"])) { + $this->getPageObject()->delete(); + + ilUtil::sendSuccess($lng->txt("wiki_page_deleted"), true); + } + + $ilCtrl->redirectByClass("ilobjwikigui", "allPages"); + } + + //// + //// Print view selection + //// + + /** + * Print view selection + * + * @param + * @return + */ + public function printViewSelection() + { + $ilUser = $this->user; + $lng = $this->lng; + $ilToolbar = $this->toolbar; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + + /*$ilToolbar->setFormAction($ilCtrl->getFormActionByClass("ilobjwikigui", "printView"), + false, "print_view"); + $ilToolbar->addFormButton($lng->txt("cont_show_print_view"), "printView"); + $ilToolbar->setCloseFormTag(false);*/ + + $this->initPrintViewSelectionForm(); + + $tpl->setContent($this->form->getHTML()); + } + + /** + * Init print view selection form. + */ + public function initPrintViewSelectionForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $pages = ilWikiPage::getAllWikiPages(ilObject::_lookupObjId($this->getWikiRefId())); + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // because of PDF export + $this->form->setPreventDoubleSubmission(false); + + //var_dump($pages); + // selection type + $radg = new ilRadioGroupInputGUI($lng->txt("cont_selection"), "sel_type"); + $radg->setValue("page"); + $op1 = new ilRadioOption($lng->txt("cont_current_page"), "page"); + $radg->addOption($op1); + $op2 = new ilRadioOption($lng->txt("wiki_whole_wiki") + . " (" . $lng->txt("wiki_pages") . ": " . count($pages) . ")", "wiki"); + $radg->addOption($op2); + $op3= new ilRadioOption($lng->txt("wiki_selected_pages"), "selection"); + $radg->addOption($op3); + + include_once("./Services/Form/classes/class.ilNestedListInputGUI.php"); + $nl = new ilNestedListInputGUI("", "obj_id"); + $op3->addSubItem($nl); + + foreach ($pages as $p) { + $nl->addListNode( + $p["id"], + $p["title"], + 0, + false, + false, + ilUtil::getImagePath("icon_pg.svg"), + $lng->txt("wiki_page") + ); + } + + $this->form->addItem($radg); + + $this->form->addCommandButton("printViewOrder", $lng->txt("wiki_show_print_view")); + $this->form->addCommandButton("pdfExportOrder", $lng->txt("wiki_show_pdf_export")); + //$this->form->setOpenTag(false); + //$this->form->setCloseTag(false); + + $this->form->setTitle($lng->txt("cont_print_selection")); + $this->form->setFormAction($ilCtrl->getFormAction($this, "printViewOrder")); + } + + public function printViewOrder() + { + $this->printViewOrderList(); + } + + public function pdfExportOrder() + { + $this->printViewOrderList(true); + } + + protected function printViewOrderList($a_pdf_export = false) + { + $ilTabs = $this->tabs; + + $pg_ids = $all_pages = array(); + + // coming from type selection + if (!is_array($_POST["wordr"])) { + switch (trim($_POST["sel_type"])) { + case "wiki": + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $all_pages = ilWikiPage::getAllWikiPages($this->getPageObject()->getWikiId()); + foreach ($all_pages as $p) { + $pg_ids[] = $p["id"]; + } + break; + + case "selection": + if (is_array($_POST["obj_id"])) { + $pg_ids = $_POST["obj_id"]; + } else { + $pg_ids[] = $_GET["wpg_id"]; + } + if (sizeof($pg_ids) > 1) { + break; + } else { + $_GET["wpg_id"] = array_pop($pg_ids); + } + // fallthrough + + // no order needed for single page + // no break + default: + //case "page": + $this->ctrl->setParameterByClass("ilObjWikiGUI", "wpg_id", $_GET["wpg_id"]); + if ($a_pdf_export) { + $this->ctrl->redirectByClass("ilObjWikiGUI", "pdfExport"); + } else { + $this->ctrl->redirectByClass("ilObjWikiGUI", "printView"); + } + break; + } + + if ($a_pdf_export) { + $this->ctrl->setParameter($this, "pexp", 1); + } + } + // refresh sorting + else { + $a_pdf_export = (bool) $_GET["pexp"]; + + asort($_POST["wordr"]); + $pg_ids = array_keys($_POST["wordr"]); + } + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $this->lng->txt("back"), + $this->ctrl->getLinkTarget($this, "preview") + ); + + if (!sizeof($all_pages)) { + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $all_pages = ilWikiPage::getAllWikiPages($this->getPageObject()->getWikiId()); + } + + include_once "Modules/Wiki/classes/class.ilWikiExportOrderTableGUI.php"; + $tbl = new ilWikiExportOrderTableGUI($this, "printViewOrderList", $a_pdf_export, $all_pages, $pg_ids); + $this->tpl->setContent($tbl->getHTML()); + } + + + //// + //// Block/Unblock + //// + + /** + * Block + */ + public function blockWikiPage() + { + $ilAccess = $this->access; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Modules/Wiki/classes/class.ilWikiPerm.php"); + if (ilWikiPerm::check("activate_wiki_protection", $_GET["ref_id"])) { + $this->getPageObject()->setBlocked(true); + $this->getPageObject()->update(); + + ilUtil::sendSuccess($lng->txt("wiki_page_blocked"), true); + } + + $ilCtrl->redirect($this, "preview"); + } + + /** + * Unblock + */ + public function unblockWikiPage() + { + $ilAccess = $this->access; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Modules/Wiki/classes/class.ilWikiPerm.php"); + if (ilWikiPerm::check("activate_wiki_protection", $_GET["ref_id"])) { + $this->getPageObject()->setBlocked(false); + $this->getPageObject()->update(); + + ilUtil::sendSuccess($lng->txt("wiki_page_unblocked"), true); + } + + $ilCtrl->redirect($this, "preview"); + } + + + //// + //// Rename + //// + + /** + * Rename wiki page form + */ + public function renameWikiPage() + { + $ilAccess = $this->access; + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (($ilAccess->checkAccess("edit_content", "", $_GET["ref_id"]) && !$this->getPageObject()->getBlocked()) + || $ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $this->initRenameForm(); + $tpl->setContent($this->form->getHTML()); + } + } + + /** + * Init renaming form. + * + * @param int $a_mode Edit Mode + */ + protected function initRenameForm() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $this->form = new ilPropertyFormGUI(); + + // new name + $ti = new ilTextInputGUI($lng->txt("wiki_new_page_name"), "new_page_name"); + $ti->setMaxLength(200); + $ti->setSize(50); + $ti->setValue($this->getPageObject()->getTitle()); + $ti->setRequired(true); + $this->form->addItem($ti); + + $this->form->addCommandButton("renamePage", $lng->txt("wiki_rename")); + $this->form->addCommandButton("preview", $lng->txt("cancel")); + + $this->form->setTitle($lng->txt("wiki_rename_page")); + $this->form->setFormAction($ilCtrl->getFormAction($this)); + } + + /** + * Rename page + */ + public function renamePage() + { + $tpl = $this->tpl; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + + $this->initRenameForm(); + if ($this->form->checkInput()) { + if (($ilAccess->checkAccess("edit_content", "", $_GET["ref_id"]) && !$this->getPageObject()->getBlocked()) + || $ilAccess->checkAccess("write", "", $_GET["ref_id"])) { + $new_name = $this->form->getInput("new_page_name"); + + $page_title = ilWikiUtil::makeDbTitle($new_name); + $pg_id = ilWikiPage::_getPageIdForWikiTitle($this->getPageObject()->getWikiId(), $page_title); + + // we might get the same page id back here, if the page + // name only differs in diacritics + // see bug http://www.ilias.de/mantis/view.php?id=11226 + if ($pg_id > 0 && $pg_id != $this->getPageObject()->getId()) { + ilUtil::sendFailure($lng->txt("wiki_page_already_exists")); + } else { + $new_name = $this->getPageObject()->rename($new_name); + $ilCtrl->setParameterByClass("ilobjwikigui", "page", ilWikiUtil::makeUrlTitle($new_name)); + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "preview"); + } + } + } + + $this->form->setValuesByPost(); + $tpl->setContent($this->form->getHtml()); + } + + //// + /// Rating + //// + + public function activateWikiPageRating() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->getPageObject()->setRating(true); + $this->getPageObject()->update(); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "preview"); + } + + public function deactivateWikiPageRating() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $this->getPageObject()->setRating(false); + $this->getPageObject()->update(); + + ilUtil::sendSuccess($lng->txt("msg_obj_modified"), true); + $ilCtrl->redirect($this, "preview"); + } + + + public function observeNoteAction($a_wiki_id, $a_page_id, $a_type, $a_action, $a_note_id) + { + // #10040 - get note text + include_once "Services/Notes/classes/class.ilNote.php"; + $note = new ilNote($a_note_id); + $note = $note->getText(); + + include_once "./Services/Notification/classes/class.ilNotification.php"; + ilWikiUtil::sendNotification("comment", ilNotification::TYPE_WIKI_PAGE, $this->getWikiRefId(), $a_page_id, $note); + } + + public function updateStatsRating($a_wiki_id, $a_wiki_type, $a_page_id, $a_page_type) + { + include_once "./Modules/Wiki/classes/class.ilWikiStat.php"; + ilWikiStat::handleEvent(ilWikiStat::EVENT_PAGE_RATING, $this->getPageObject()); + } + + + // + // advanced meta data + // + + protected function initAdvancedMetaDataForm() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + $page = $this->getWikiPage(); + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this, "updateAdvancedMetaData")); + + // :TODO: + $form->setTitle($lng->txt("wiki_advmd_block_title") . ": " . $page->getTitle()); + + include_once('Services/AdvancedMetaData/classes/class.ilAdvancedMDRecordGUI.php'); + $this->record_gui = new ilAdvancedMDRecordGUI(ilAdvancedMDRecordGUI::MODE_EDITOR, 'wiki', $page->getWikiId(), 'wpg', $page->getId()); + $this->record_gui->setPropertyForm($form); + $this->record_gui->parse(); + + $form->addCommandButton("updateAdvancedMetaData", $lng->txt("save")); + $form->addCommandButton("preview", $lng->txt("cancel")); + + return $form; + } + + public function editAdvancedMetaData(ilPropertyFormGUI $a_form = null) + { + $ilTabs = $this->tabs; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + $tpl = $this->tpl; + $ilAccess = $this->access; + + if (!$ilAccess->checkAccess("write", "", $this->wiki_ref_id) && + !$ilAccess->checkAccess("edit_page_meta", "", $this->wiki_ref_id)) { + return; + } + + + $ilTabs->clearTargets(); + $ilTabs->setBackTarget( + $lng->txt("back"), + $ilCtrl->getLinkTarget($this, "preview") + ); + + if (!$a_form) { + $a_form = $this->initAdvancedMetaDataForm(); + } + + $tpl->setContent($a_form->getHTML()); + } + + public function updateAdvancedMetaData() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilAccess = $this->access; + + if (!$ilAccess->checkAccess("write", "", $this->wiki_ref_id) && + !$ilAccess->checkAccess("edit_page_meta", "", $this->wiki_ref_id)) { + return; + } + + $form = $this->initAdvancedMetaDataForm(); + + // needed for proper advanced MD validation + $form->checkInput(); + if (!$this->record_gui->importEditFormPostValues()) { + $this->editAdvancedMetaData($form); // #16470 + return false; + } + + if ($this->record_gui->writeEditForm()) { + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + } + $ilCtrl->redirect($this, "preview"); + } + + public function hideAdvancedMetaData() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilAccess = $this->access; + + if (!$ilAccess->checkAccess("write", "", $this->wiki_ref_id) && + !$ilAccess->checkAccess("edit_page_meta", "", $this->wiki_ref_id)) { + return; + } + + $this->getPageObject()->hideAdvancedMetadata(true); + $this->getPageObject()->update(); + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "preview"); + } + + public function unhideAdvancedMetaData() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilAccess = $this->access; + + if (!$ilAccess->checkAccess("write", "", $this->wiki_ref_id) && + !$ilAccess->checkAccess("edit_page_meta", "", $this->wiki_ref_id)) { + return; + } + + $this->getPageObject()->hideAdvancedMetadata(false); + $this->getPageObject()->update(); + + ilUtil::sendSuccess($lng->txt("settings_saved"), true); + $ilCtrl->redirect($this, "preview"); + } + + /** + * Edit + * + * @param + * @return + */ + public function edit() + { + $tpl = $this->tpl; + $lng = $this->lng; + + self::initEditingJS($tpl); + + return parent::edit(); + } + + /** + * Init wiki editing js + * + * @param ilTemplate $a_tpl template + */ + public static function initEditingJS(ilTemplate $a_tpl) + { + global $DIC; + + $lng = $DIC->language(); + + $a_tpl->addJavascript("./Modules/Wiki/js/WikiEdit.js"); + $a_tpl->addOnLoadCode("il.Wiki.Edit.txt.page_exists = '" . $lng->txt("wiki_page_exists") . "';"); + $a_tpl->addOnLoadCode("il.Wiki.Edit.txt.new_page = '" . $lng->txt("wiki_new_page") . "';"); + } + + + /** + * Returns form to insert a wiki link per ajax + */ + public function insertWikiLink() + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + include_once("Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->addCommandButton("addWikiLink", $lng->txt("wiki_add_link")); + $form->addCommandButton("searchWikiLink", $lng->txt("search")); + + // Target page + $tp = new ilTextInputGUI($this->lng->txt("wiki_target_page"), "target_page"); + $tp->setSize(18); + $tp->setRequired(true); + $tp->setInfo("..."); + $tp->setDataSource($ilCtrl->getLinkTarget($this, "insertWikiLinkAC", "", true)); + $form->addItem($tp); + + // Link text + $lt = new ilTextInputGUI($this->lng->txt("wiki_link_text"), "link_text"); + $lt->setSize(18); + $form->addItem($lt); + + //$form->setTitle($lng->txt("wiki_link")); + + echo $form->getHTML(); + exit; + } + + /** + * Auto complete for insert wiki link + */ + public function insertWikiLinkAC() + { + $result = array(); + + $term = $_GET["term"]; + + // if page exists, make it first entry + if (ilWikiPage::_wikiPageExists($this->getPageObject()->getParentId(), $term)) { + $entry = new stdClass(); + $entry->value = $term; + $entry->label = $term; + $result[] = $entry; + } + + $res = ilWikiPage::getPagesForSearch($this->getPageObject()->getParentId(), $term); + + $cnt = 0; + foreach ($res as $r) { + if ($result[0]->value == $r) { + continue; + } + if ($cnt++ > 19) { + continue; + } + $entry = new stdClass(); + $entry->value = $r; + $entry->label = $r; + $result[] = $entry; + } + + include_once './Services/JSON/classes/class.ilJsonUtil.php'; + echo ilJsonUtil::encode($result); + exit; + } + + /** + * Search wiki link list + */ + public function searchWikiLinkAC() + { + $lng = $this->lng; + + $lng->loadLanguageModule("wiki"); + + $tpl = new ilTemplate("tpl.wiki_ac_search_result.html", true, true, "Modules/Wiki"); + $term = trim($_GET["term"]); + + $pages = ilObjWiki::_performSearch($this->getPageObject()->getParentId(), $term); + + $found = array(); + foreach ($pages as $page) { + $found[] = array("page_id" => $page["page_id"], "title" => ilWikiPage::lookupTitle($page["page_id"])); + } + + // sort if all pages are listed + if ($term == "") { + $found = ilUtil::sortArray($found, "title", "asc"); + } + + foreach ($found as $f) { + $tpl->setCurrentBlock("item"); + $tpl->setVariable("WIKI_TITLE", $f["title"]); + $tpl->parseCurrentBlock(); + } + + if (count($pages) == 0) { + $tpl->setVariable("INFOTEXT", str_replace("$1", $term, $lng->txt("wiki_no_page_found"))); + } elseif ($term == '') { + $tpl->setVariable("INFOTEXT", $lng->txt("wiki_no_search_term"), $term); + } else { + $tpl->setVariable("INFOTEXT", str_replace("$1", $term, $lng->txt("wiki_pages_found"))); + } + + $tpl->setVariable("TXT_BACK", $lng->txt("back")); + echo $tpl->get(); + exit; + } + + // + // exercise assignment + // + + /** + * Finalize and submit blog to exercise + */ + protected function finalizeAssignment() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + include_once("./Modules/Exercise/AssignmentTypes/classes/class.ilExAssignmentTypes.php"); + include_once("./Modules/Exercise/classes/class.ilExAssignment.php"); + $wiki_ass = ilExAssignmentTypes::getInstance()->getById(ilExAssignment::TYPE_WIKI_TEAM); + + $ass_id = (int) $_GET["ass"]; + $wiki_ass->submitWiki($ass_id, $this->user->getId(), $this->getWikiRefId()); + + /* + include_once "Modules/Exercise/classes/class.ilExSubmissionBaseGUI.php"; + include_once "Modules/Exercise/classes/class.ilExSubmissionObjectGUI.php"; + $exc_gui = ilExSubmissionObjectGUI::initGUIForSubmit($this->ass_id); + $exc_gui->submitBlog($this->node_id);*/ + + ilUtil::sendSuccess($lng->txt("wiki_finalized"), true); + $ilCtrl->redirect($this, "preview"); + } + + protected function downloadExcSubFile() + { + $ilUser = $this->user; + + $ass_id = (int) $_GET["ass"]; + $ass = new ilExAssignment($ass_id); + $submission = new ilExSubmission($ass, $ilUser->getId()); + $submitted = $submission->getFiles(); + if (count($submitted) > 0) { + $submitted = array_pop($submitted); + + $user_data = ilObjUser::_lookupName($submitted["user_id"]); + $title = ilObject::_lookupTitle($submitted["obj_id"]) . " - " . + $ass->getTitle() . " (Team " . $submission->getTeam()->getId() . ").zip"; + + ilUtil::deliverFile($submitted["filename"], $title); + } + } +} diff --git a/Modules/Wiki/classes/class.ilWikiPageTemplate.php b/Modules/Wiki/classes/class.ilWikiPageTemplate.php index 8e7e5ebed2602c789db25e01971ab80ca68853e0..2b6524147a63b277a8fa0b44a075192b3b23d616 100644 --- a/Modules/Wiki/classes/class.ilWikiPageTemplate.php +++ b/Modules/Wiki/classes/class.ilWikiPageTemplate.php @@ -11,128 +11,122 @@ */ class ilWikiPageTemplate { - /** - * @var ilDB - */ - protected $db; + /** + * @var ilDB + */ + protected $db; - const TYPE_ALL = 0; - const TYPE_NEW_PAGES = 1; - const TYPE_ADD_TO_PAGE = 2; + const TYPE_ALL = 0; + const TYPE_NEW_PAGES = 1; + const TYPE_ADD_TO_PAGE = 2; - protected $wiki_id; - protected $ilDB; + protected $wiki_id; + protected $ilDB; - /** - * Constructor - * - * @param int $a_wiki_id wiki id - */ - function __construct($a_wiki_id) - { - global $DIC; + /** + * Constructor + * + * @param int $a_wiki_id wiki id + */ + public function __construct($a_wiki_id) + { + global $DIC; - $ilDB = $DIC->database(); + $ilDB = $DIC->database(); - $this->wiki_id = $a_wiki_id; - $this->db = $ilDB; - } + $this->wiki_id = $a_wiki_id; + $this->db = $ilDB; + } - /** - * Get all info - */ - function getAllInfo($a_type = self::TYPE_ALL) - { - $and = ""; - if ($a_type == self::TYPE_NEW_PAGES) - { - $and = " AND t.new_pages = ".$this->db->quote(1, "integer"); - } - if ($a_type == self::TYPE_ADD_TO_PAGE) - { - $and = " AND t.add_to_page = ".$this->db->quote(1, "integer"); - } + /** + * Get all info + */ + public function getAllInfo($a_type = self::TYPE_ALL) + { + $and = ""; + if ($a_type == self::TYPE_NEW_PAGES) { + $and = " AND t.new_pages = " . $this->db->quote(1, "integer"); + } + if ($a_type == self::TYPE_ADD_TO_PAGE) { + $and = " AND t.add_to_page = " . $this->db->quote(1, "integer"); + } - $set = $this->db->query($q = "SELECT t.wiki_id, t.wpage_id, p.title, t.new_pages, t.add_to_page FROM wiki_page_template t JOIN il_wiki_page p ON ". - " (t.wpage_id = p.id) ". - " WHERE t.wiki_id = ".$this->db->quote($this->wiki_id, "integer"). - $and - ); - $templates = array(); - while ($rec = $this->db->fetchAssoc($set)) - { - $templates[] = $rec; - } - return $templates; - } + $set = $this->db->query( + $q = "SELECT t.wiki_id, t.wpage_id, p.title, t.new_pages, t.add_to_page FROM wiki_page_template t JOIN il_wiki_page p ON " . + " (t.wpage_id = p.id) " . + " WHERE t.wiki_id = " . $this->db->quote($this->wiki_id, "integer") . + $and + ); + $templates = array(); + while ($rec = $this->db->fetchAssoc($set)) { + $templates[] = $rec; + } + return $templates; + } - /** - * Add wiki page template - * - * @param int $a_id wiki page id - */ - function save($a_id, $a_new_pages = 0, $a_add_to_page = 0) - { - if ($a_id <= 0) - { - return; - } + /** + * Add wiki page template + * + * @param int $a_id wiki page id + */ + public function save($a_id, $a_new_pages = 0, $a_add_to_page = 0) + { + if ($a_id <= 0) { + return; + } - $set = $this->db->query("SELECT * FROM wiki_page_template ". - " WHERE wiki_id = ".$this->db->quote($this->wiki_id, "integer"). - " AND wpage_id = ".$this->db->quote($a_id, "integer") - ); - if (!$this->db->fetchAssoc($set)) - { - $this->db->manipulate("INSERT INTO wiki_page_template ". - "(wiki_id, wpage_id, new_pages, add_to_page) VALUES (". - $this->db->quote($this->wiki_id, "integer").",". - $this->db->quote($a_id, "integer").",". - $this->db->quote($a_new_pages, "integer").",". - $this->db->quote($a_add_to_page, "integer"). - ")"); - } - else - { - $this->db->manipulate("UPDATE wiki_page_template SET ". - " new_pages = ".$this->db->quote($a_new_pages, "integer").",". - " add_to_page = ".$this->db->quote($a_add_to_page, "integer"). - " WHERE wiki_id = ".$this->db->quote($this->wiki_id, "integer"). - " AND wpage_id = ".$this->db->quote($a_id, "integer") - ); - } - } - - /** - * Remove template status of a page - * - * @param int $a_id wiki page id - */ - function remove($a_id) - { - $this->db->manipulate("DELETE FROM wiki_page_template WHERE ". - " wiki_id = ".$this->db->quote($this->wiki_id, "integer"). - " AND wpage_id = ".$this->db->quote($a_id, "integer") - ); - } - - /** - * Is page set as template? - * - * @param int $a_id wiki page id - * @return type bool - */ - function isPageTemplate($a_id) - { - $set = $this->db->query("SELECT t.wpage_id". - " FROM wiki_page_template t". - " JOIN il_wiki_page p ON ". - " (t.wpage_id = p.id) ". - " WHERE t.wiki_id = ".$this->db->quote($this->wiki_id, "integer"). - " AND p.id = ".$this->db->quote($a_id, "integer")); - return (bool)$this->db->numRows($set); - } + $set = $this->db->query( + "SELECT * FROM wiki_page_template " . + " WHERE wiki_id = " . $this->db->quote($this->wiki_id, "integer") . + " AND wpage_id = " . $this->db->quote($a_id, "integer") + ); + if (!$this->db->fetchAssoc($set)) { + $this->db->manipulate("INSERT INTO wiki_page_template " . + "(wiki_id, wpage_id, new_pages, add_to_page) VALUES (" . + $this->db->quote($this->wiki_id, "integer") . "," . + $this->db->quote($a_id, "integer") . "," . + $this->db->quote($a_new_pages, "integer") . "," . + $this->db->quote($a_add_to_page, "integer") . + ")"); + } else { + $this->db->manipulate( + "UPDATE wiki_page_template SET " . + " new_pages = " . $this->db->quote($a_new_pages, "integer") . "," . + " add_to_page = " . $this->db->quote($a_add_to_page, "integer") . + " WHERE wiki_id = " . $this->db->quote($this->wiki_id, "integer") . + " AND wpage_id = " . $this->db->quote($a_id, "integer") + ); + } + } + /** + * Remove template status of a page + * + * @param int $a_id wiki page id + */ + public function remove($a_id) + { + $this->db->manipulate( + "DELETE FROM wiki_page_template WHERE " . + " wiki_id = " . $this->db->quote($this->wiki_id, "integer") . + " AND wpage_id = " . $this->db->quote($a_id, "integer") + ); + } + + /** + * Is page set as template? + * + * @param int $a_id wiki page id + * @return type bool + */ + public function isPageTemplate($a_id) + { + $set = $this->db->query("SELECT t.wpage_id" . + " FROM wiki_page_template t" . + " JOIN il_wiki_page p ON " . + " (t.wpage_id = p.id) " . + " WHERE t.wiki_id = " . $this->db->quote($this->wiki_id, "integer") . + " AND p.id = " . $this->db->quote($a_id, "integer")); + return (bool) $this->db->numRows($set); + } } - -?> \ No newline at end of file diff --git a/Modules/Wiki/classes/class.ilWikiPageTemplateGUI.php b/Modules/Wiki/classes/class.ilWikiPageTemplateGUI.php index 6454120affb8577ea2d7afc041a08e250824e944..2cdc6c18a77ddabbd845f2307262efefec34f642 100644 --- a/Modules/Wiki/classes/class.ilWikiPageTemplateGUI.php +++ b/Modules/Wiki/classes/class.ilWikiPageTemplateGUI.php @@ -11,194 +11,181 @@ */ class ilWikiPageTemplateGUI { - /** - * @var ilToolbarGUI - */ - protected $toolbar; - - /** - * @var ilLanguage - */ - protected $lng; - - protected $wiki_gui; - protected $ctrl; - protected $tpl; - - /** - * Constructor - * - * @param ilObjWikiGUI $a_wiki_gui wiki gui object - */ - function __construct(ilObjWikiGUI $a_wiki_gui) - { - global $DIC; - - $ilCtrl = $DIC->ctrl(); - $tpl = $DIC["tpl"]; - $ilToolbar = $DIC->toolbar(); - $lng = $DIC->language(); - - $this->wiki_gui = $a_wiki_gui; - $this->wiki = $this->wiki_gui->object; - $this->ctrl = $ilCtrl; - $this->tpl = $tpl; - $this->lng = $lng; - $this->toolbar = $ilToolbar; - } - - /** - * Execute command - */ - function executeCommand() - { - $nc = $this->ctrl->getNextClass(); - - switch($nc) - { - default: - $cmd = $this->ctrl->getCmd("listTemplates"); - if (in_array($cmd, array("listTemplates", "add", "remove", "saveTemplateSettings", "addPageTemplateFromPageAction", "removePageTemplateFromPageAction"))) - { - $this->$cmd(); - } - break; - } - } - - /** - * List templates - */ - function listTemplates() - { - // list pages - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $pages = ilWikiPage::getAllWikiPages($this->wiki->getId()); - $options = array("" => $this->lng->txt("please_select")); - foreach ($pages as $p) - { - //if (!in_array($p["id"], $ipages_ids)) - //{ - $options[$p["id"]] = ilUtil::shortenText($p["title"], 60, true); - //} - } - - $this->toolbar->setFormAction($this->ctrl->getFormAction($this)); - $this->toolbar->setOpenFormTag(true); - $this->toolbar->setCloseFormTag(false); - - if (count($options) > 0) - { - include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); - $si = new ilSelectInputGUI($this->lng->txt("wiki_pages"), "templ_page_id"); - $si->setOptions($options); - $this->toolbar->addInputItem($si); - $this->toolbar->addFormButton($this->lng->txt("wiki_add_template"), "add"); - $this->toolbar->addSeparator(); - - } - - // empty page as template? - include_once("./Services/Form/classes/class.ilCheckboxInputGUI.php"); - $cb = new ilCheckboxInputGUI($this->lng->txt("wiki_empty_page_template"), "empty_page_templ"); - $cb->setChecked($this->wiki->getEmptyPageTemplate()); - $this->toolbar->addInputItem($cb, true); - $this->toolbar->addFormButton($this->lng->txt("save"), "saveTemplateSettings"); - - - include_once("./Modules/Wiki/classes/class.ilWikiPageTemplatesTableGUI.php"); - $tab = new ilWikiPageTemplatesTableGUI($this, "listTemplates", $this->wiki->getId()); - $tab->setOpenFormTag(false); - $tab->setCloseFormTag(true); - $this->tpl->setContent($tab->getHTML()); - } - - /** - * Add page as template page - */ - function add() - { - include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); - $wpt = new ilWikiPageTemplate($this->wiki->getId()); - $wpt->save((int) $_POST["templ_page_id"]); - ilUtil::sendSuccess($this->lng->txt("wiki_template_added"), true); - $this->ctrl->redirect($this, "listTemplates"); - } - - /** - * Remove - */ - function remove() - { - include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); - $wpt = new ilWikiPageTemplate($this->wiki->getId()); - - if (is_array($_POST["id"])) - { - foreach ($_POST["id"] as $id) - { - $wpt->remove((int) $id); - } - ilUtil::sendSuccess($this->lng->txt("wiki_template_status_removed"), true); - } - - $this->ctrl->redirect($this, "listTemplates"); - } - - /** - * Save template settings - */ - function saveTemplateSettings() - { - if (is_array($_POST["all_ids"])) - { - include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); - foreach ($_POST["all_ids"] as $id) - { - $wpt = new ilWikiPageTemplate($this->wiki->getId()); - $wpt->save((int) $id, (int) $_POST["new_pages"][$id], (int) $_POST["add_to_page"][$id]); - } - } - - $this->wiki->setEmptyPageTemplate((int) $_POST["empty_page_templ"]); - $this->wiki->update(); - - ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); - $this->ctrl->redirect($this, "listTemplates"); - } - - - // - // PAGE ACTIONS - // - - function removePageTemplateFromPageAction() - { - $page_id = (int)$_GET["wpg_id"]; - if($page_id) - { - include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); - $wpt = new ilWikiPageTemplate($this->wiki->getId()); - $wpt->remove($page_id); - ilUtil::sendSuccess($this->lng->txt("wiki_template_status_removed"), true); - } - - $this->ctrl->redirect($this, "listTemplates"); - } - - function addPageTemplateFromPageAction() - { - $page_id = (int)$_GET["wpg_id"]; - if($page_id) - { - include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); - $wpt = new ilWikiPageTemplate($this->wiki->getId()); - $wpt->save($page_id); - ilUtil::sendSuccess($this->lng->txt("wiki_template_added"), true); - } - - $this->ctrl->redirect($this, "listTemplates"); - } + /** + * @var ilToolbarGUI + */ + protected $toolbar; + + /** + * @var ilLanguage + */ + protected $lng; + + protected $wiki_gui; + protected $ctrl; + protected $tpl; + + /** + * Constructor + * + * @param ilObjWikiGUI $a_wiki_gui wiki gui object + */ + public function __construct(ilObjWikiGUI $a_wiki_gui) + { + global $DIC; + + $ilCtrl = $DIC->ctrl(); + $tpl = $DIC["tpl"]; + $ilToolbar = $DIC->toolbar(); + $lng = $DIC->language(); + + $this->wiki_gui = $a_wiki_gui; + $this->wiki = $this->wiki_gui->object; + $this->ctrl = $ilCtrl; + $this->tpl = $tpl; + $this->lng = $lng; + $this->toolbar = $ilToolbar; + } + + /** + * Execute command + */ + public function executeCommand() + { + $nc = $this->ctrl->getNextClass(); + + switch ($nc) { + default: + $cmd = $this->ctrl->getCmd("listTemplates"); + if (in_array($cmd, array("listTemplates", "add", "remove", "saveTemplateSettings", "addPageTemplateFromPageAction", "removePageTemplateFromPageAction"))) { + $this->$cmd(); + } + break; + } + } + + /** + * List templates + */ + public function listTemplates() + { + // list pages + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $pages = ilWikiPage::getAllWikiPages($this->wiki->getId()); + $options = array("" => $this->lng->txt("please_select")); + foreach ($pages as $p) { + //if (!in_array($p["id"], $ipages_ids)) + //{ + $options[$p["id"]] = ilUtil::shortenText($p["title"], 60, true); + //} + } + + $this->toolbar->setFormAction($this->ctrl->getFormAction($this)); + $this->toolbar->setOpenFormTag(true); + $this->toolbar->setCloseFormTag(false); + + if (count($options) > 0) { + include_once("./Services/Form/classes/class.ilSelectInputGUI.php"); + $si = new ilSelectInputGUI($this->lng->txt("wiki_pages"), "templ_page_id"); + $si->setOptions($options); + $this->toolbar->addInputItem($si); + $this->toolbar->addFormButton($this->lng->txt("wiki_add_template"), "add"); + $this->toolbar->addSeparator(); + } + + // empty page as template? + include_once("./Services/Form/classes/class.ilCheckboxInputGUI.php"); + $cb = new ilCheckboxInputGUI($this->lng->txt("wiki_empty_page_template"), "empty_page_templ"); + $cb->setChecked($this->wiki->getEmptyPageTemplate()); + $this->toolbar->addInputItem($cb, true); + $this->toolbar->addFormButton($this->lng->txt("save"), "saveTemplateSettings"); + + + include_once("./Modules/Wiki/classes/class.ilWikiPageTemplatesTableGUI.php"); + $tab = new ilWikiPageTemplatesTableGUI($this, "listTemplates", $this->wiki->getId()); + $tab->setOpenFormTag(false); + $tab->setCloseFormTag(true); + $this->tpl->setContent($tab->getHTML()); + } + + /** + * Add page as template page + */ + public function add() + { + include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); + $wpt = new ilWikiPageTemplate($this->wiki->getId()); + $wpt->save((int) $_POST["templ_page_id"]); + ilUtil::sendSuccess($this->lng->txt("wiki_template_added"), true); + $this->ctrl->redirect($this, "listTemplates"); + } + + /** + * Remove + */ + public function remove() + { + include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); + $wpt = new ilWikiPageTemplate($this->wiki->getId()); + + if (is_array($_POST["id"])) { + foreach ($_POST["id"] as $id) { + $wpt->remove((int) $id); + } + ilUtil::sendSuccess($this->lng->txt("wiki_template_status_removed"), true); + } + + $this->ctrl->redirect($this, "listTemplates"); + } + + /** + * Save template settings + */ + public function saveTemplateSettings() + { + if (is_array($_POST["all_ids"])) { + include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); + foreach ($_POST["all_ids"] as $id) { + $wpt = new ilWikiPageTemplate($this->wiki->getId()); + $wpt->save((int) $id, (int) $_POST["new_pages"][$id], (int) $_POST["add_to_page"][$id]); + } + } + + $this->wiki->setEmptyPageTemplate((int) $_POST["empty_page_templ"]); + $this->wiki->update(); + + ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true); + $this->ctrl->redirect($this, "listTemplates"); + } + + + // + // PAGE ACTIONS + // + + public function removePageTemplateFromPageAction() + { + $page_id = (int) $_GET["wpg_id"]; + if ($page_id) { + include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); + $wpt = new ilWikiPageTemplate($this->wiki->getId()); + $wpt->remove($page_id); + ilUtil::sendSuccess($this->lng->txt("wiki_template_status_removed"), true); + } + + $this->ctrl->redirect($this, "listTemplates"); + } + + public function addPageTemplateFromPageAction() + { + $page_id = (int) $_GET["wpg_id"]; + if ($page_id) { + include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); + $wpt = new ilWikiPageTemplate($this->wiki->getId()); + $wpt->save($page_id); + ilUtil::sendSuccess($this->lng->txt("wiki_template_added"), true); + } + + $this->ctrl->redirect($this, "listTemplates"); + } } - -?> \ No newline at end of file diff --git a/Modules/Wiki/classes/class.ilWikiPageTemplatesTableGUI.php b/Modules/Wiki/classes/class.ilWikiPageTemplatesTableGUI.php index d1ff0478879469f2c0e85c587d6fcbd67fd50316..11993d900a6052f825633648059c376a87034352 100644 --- a/Modules/Wiki/classes/class.ilWikiPageTemplatesTableGUI.php +++ b/Modules/Wiki/classes/class.ilWikiPageTemplatesTableGUI.php @@ -14,63 +14,59 @@ include_once("./Services/Table/classes/class.ilTable2GUI.php"); */ class ilWikiPageTemplatesTableGUI extends ilTable2GUI { - /** - * @var ilAccessHandler - */ - protected $access; + /** + * @var ilAccessHandler + */ + protected $access; - /** - * Constructor - */ - function __construct($a_parent_obj, $a_parent_cmd, $a_wiki_id) - { - global $DIC; + /** + * Constructor + */ + public function __construct($a_parent_obj, $a_parent_cmd, $a_wiki_id) + { + global $DIC; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->access = $DIC->access(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - $ilAccess = $DIC->access(); - $lng = $DIC->language(); + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->access = $DIC->access(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + $ilAccess = $DIC->access(); + $lng = $DIC->language(); - parent::__construct($a_parent_obj, $a_parent_cmd); - include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); - $templates = new ilWikiPageTemplate($a_wiki_id); - $this->setData($templates->getAllInfo()); - $this->setTitle($lng->txt("")); + parent::__construct($a_parent_obj, $a_parent_cmd); + include_once("./Modules/Wiki/classes/class.ilWikiPageTemplate.php"); + $templates = new ilWikiPageTemplate($a_wiki_id); + $this->setData($templates->getAllInfo()); + $this->setTitle($lng->txt("")); - $this->addColumn($this->lng->txt(""), "", "1"); - $this->addColumn($this->lng->txt("title"), "title"); - $this->addColumn($this->lng->txt("wiki_templ_new_pages"), ""); - $this->addColumn($this->lng->txt("wiki_templ_add_to_page"), ""); + $this->addColumn($this->lng->txt(""), "", "1"); + $this->addColumn($this->lng->txt("title"), "title"); + $this->addColumn($this->lng->txt("wiki_templ_new_pages"), ""); + $this->addColumn($this->lng->txt("wiki_templ_add_to_page"), ""); - $this->setDefaultOrderDirection("asc"); - $this->setDefaultOrderField("title"); + $this->setDefaultOrderDirection("asc"); + $this->setDefaultOrderField("title"); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.wiki_page_templates_row.html", "Modules/Wiki"); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate("tpl.wiki_page_templates_row.html", "Modules/Wiki"); - $this->addMultiCommand("remove", $lng->txt("wiki_remove_template_status")); - $this->addCommandButton("saveTemplateSettings", $lng->txt("save")); - } - - /** - * Fill table row - */ - protected function fillRow($a_set) - { - $this->tpl->setVariable("ID", $a_set["wpage_id"]); - $this->tpl->setVariable("TITLE", $a_set["title"]); - if ($a_set["new_pages"]) - { - $this->tpl->setVariable("NEW_PAGES_CHECKED", 'checked="checked"'); - } - if ($a_set["add_to_page"]) - { - $this->tpl->setVariable("ADD_TO_PAGE_CHECKED", 'checked="checked"'); - } - } + $this->addMultiCommand("remove", $lng->txt("wiki_remove_template_status")); + $this->addCommandButton("saveTemplateSettings", $lng->txt("save")); + } + /** + * Fill table row + */ + protected function fillRow($a_set) + { + $this->tpl->setVariable("ID", $a_set["wpage_id"]); + $this->tpl->setVariable("TITLE", $a_set["title"]); + if ($a_set["new_pages"]) { + $this->tpl->setVariable("NEW_PAGES_CHECKED", 'checked="checked"'); + } + if ($a_set["add_to_page"]) { + $this->tpl->setVariable("ADD_TO_PAGE_CHECKED", 'checked="checked"'); + } + } } -?> \ No newline at end of file diff --git a/Modules/Wiki/classes/class.ilWikiPagesTableGUI.php b/Modules/Wiki/classes/class.ilWikiPagesTableGUI.php index 147125f7cb2499cdc8f5a32a2ba52256d7553aee..deac2a0732b57b84dc6c34a6a1fe6a7261cd1f75 100755 --- a/Modules/Wiki/classes/class.ilWikiPagesTableGUI.php +++ b/Modules/Wiki/classes/class.ilWikiPagesTableGUI.php @@ -4,11 +4,11 @@ include_once("Services/Table/classes/class.ilTable2GUI.php"); -define ("IL_WIKI_ALL_PAGES", "all"); -define ("IL_WIKI_NEW_PAGES", "new"); -define ("IL_WIKI_POPULAR_PAGES", "popular"); -define ("IL_WIKI_WHAT_LINKS_HERE", "what_links"); -define ("IL_WIKI_ORPHANED_PAGES", "orphaned"); +define("IL_WIKI_ALL_PAGES", "all"); +define("IL_WIKI_NEW_PAGES", "new"); +define("IL_WIKI_POPULAR_PAGES", "popular"); +define("IL_WIKI_WHAT_LINKS_HERE", "what_links"); +define("IL_WIKI_ORPHANED_PAGES", "orphaned"); /** * TableGUI class for wiki pages table @@ -20,167 +20,178 @@ define ("IL_WIKI_ORPHANED_PAGES", "orphaned"); */ class ilWikiPagesTableGUI extends ilTable2GUI { - - function __construct($a_parent_obj, $a_parent_cmd = "", - $a_wiki_id, $a_mode = IL_WIKI_ALL_PAGES, $a_page_id = 0) - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->pg_list_mode = $a_mode; - $this->wiki_id = $a_wiki_id; - $this->page_id = $a_page_id; - - switch($this->pg_list_mode) - { - case IL_WIKI_NEW_PAGES: - $this->addColumn($lng->txt("created"), "created", "33%"); - $this->addColumn($lng->txt("wiki_page"), "title", "33%"); - $this->addColumn($lng->txt("wiki_created_by"), "user_sort", "34%"); - $this->setRowTemplate("tpl.table_row_wiki_new_page.html", - "Modules/Wiki"); - break; - - case IL_WIKI_POPULAR_PAGES: - $this->addColumn($lng->txt("wiki_page"), "title", "50%"); - $this->addColumn($lng->txt("wiki_page_hits"), "cnt", "50%"); - $this->setRowTemplate("tpl.table_row_wiki_popular_page.html", - "Modules/Wiki"); - break; - - case IL_WIKI_ORPHANED_PAGES: - $this->addColumn($lng->txt("wiki_page"), "title", "100%"); - $this->setRowTemplate("tpl.table_row_wiki_orphaned_page.html", - "Modules/Wiki"); - break; - - default: - $this->addColumn($lng->txt("wiki_page"), "title", "33%"); - $this->addColumn($lng->txt("wiki_last_changed"), "date", "33%"); - $this->addColumn($lng->txt("wiki_last_changed_by"), "user_sort", "34%"); - $this->setRowTemplate("tpl.table_row_wiki_page.html", - "Modules/Wiki"); - break; - } - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->getPages(); - - $this->setShowRowsSelector(true); - - switch($this->pg_list_mode) - { - case IL_WIKI_WHAT_LINKS_HERE: - $this->setTitle(sprintf($lng->txt("wiki_what_links_to_page"), - ilWikiPage::lookupTitle($this->page_id))); - break; - - default: - $this->setTitle($lng->txt("wiki_".$a_mode."_pages")); - break; - } - } - - /** - * Get pages for list. - */ - function getPages() - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - - $pages = array(); - $this->setDefaultOrderField("title"); - - switch ($this->pg_list_mode) - { - case IL_WIKI_WHAT_LINKS_HERE: - $pages = ilWikiPage::getLinksToPage($this->wiki_id, $this->page_id); - break; - - case IL_WIKI_ALL_PAGES: - $pages = ilWikiPage::getAllWikiPages($this->wiki_id); - break; - - case IL_WIKI_NEW_PAGES: - $this->setDefaultOrderField("created"); - $this->setDefaultOrderDirection("desc"); - $pages = ilWikiPage::getNewWikiPages($this->wiki_id); - break; - - case IL_WIKI_POPULAR_PAGES: - $this->setDefaultOrderField("cnt"); - $this->setDefaultOrderDirection("desc"); - $pages = ilWikiPage::getPopularPages($this->wiki_id); - break; - - case IL_WIKI_ORPHANED_PAGES: - $pages = ilWikiPage::getOrphanedPages($this->wiki_id); - break; - } - - if($pages) - { - // enable sorting - include_once("./Services/User/classes/class.ilUserUtil.php"); - foreach(array_keys($pages) as $idx) - { - $pages[$idx]["user_sort"] = ilUserUtil::getNamePresentation($pages[$idx]["user"], false, false); - } - } - - $this->setData($pages); - } - - function numericOrdering($a_field) - { - if ($a_field == "cnt") - { - return true; - } - return false; - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - if ($this->pg_list_mode == IL_WIKI_NEW_PAGES) - { - $this->tpl->setVariable("TXT_PAGE_TITLE", $a_set["title"]); - $this->tpl->setVariable("DATE", - ilDatePresentation::formatDate(new ilDateTime($a_set["created"], IL_CAL_DATETIME))); - } - else if ($this->pg_list_mode == IL_WIKI_POPULAR_PAGES) - { - $this->tpl->setVariable("TXT_PAGE_TITLE", $a_set["title"]); - $this->tpl->setVariable("HITS", $a_set["cnt"]); - } - else - { - $this->tpl->setVariable("TXT_PAGE_TITLE", $a_set["title"]); - $this->tpl->setVariable("DATE", - ilDatePresentation::formatDate(new ilDateTime($a_set["date"], IL_CAL_DATETIME))); - } - $this->tpl->setVariable("HREF_PAGE", - ilObjWikiGUI::getGotoLink($_GET["ref_id"], $a_set["title"])); - - // user name - include_once("./Services/User/classes/class.ilUserUtil.php"); - $this->tpl->setVariable("TXT_USER", - ilUserUtil::getNamePresentation($a_set["user"], true, true, - $ilCtrl->getLinkTarget($this->getParentObject(), $this->getParentCmd()) - )); - } - + public function __construct( + $a_parent_obj, + $a_parent_cmd = "", + $a_wiki_id, + $a_mode = IL_WIKI_ALL_PAGES, + $a_page_id = 0 + ) { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->pg_list_mode = $a_mode; + $this->wiki_id = $a_wiki_id; + $this->page_id = $a_page_id; + + switch ($this->pg_list_mode) { + case IL_WIKI_NEW_PAGES: + $this->addColumn($lng->txt("created"), "created", "33%"); + $this->addColumn($lng->txt("wiki_page"), "title", "33%"); + $this->addColumn($lng->txt("wiki_created_by"), "user_sort", "34%"); + $this->setRowTemplate( + "tpl.table_row_wiki_new_page.html", + "Modules/Wiki" + ); + break; + + case IL_WIKI_POPULAR_PAGES: + $this->addColumn($lng->txt("wiki_page"), "title", "50%"); + $this->addColumn($lng->txt("wiki_page_hits"), "cnt", "50%"); + $this->setRowTemplate( + "tpl.table_row_wiki_popular_page.html", + "Modules/Wiki" + ); + break; + + case IL_WIKI_ORPHANED_PAGES: + $this->addColumn($lng->txt("wiki_page"), "title", "100%"); + $this->setRowTemplate( + "tpl.table_row_wiki_orphaned_page.html", + "Modules/Wiki" + ); + break; + + default: + $this->addColumn($lng->txt("wiki_page"), "title", "33%"); + $this->addColumn($lng->txt("wiki_last_changed"), "date", "33%"); + $this->addColumn($lng->txt("wiki_last_changed_by"), "user_sort", "34%"); + $this->setRowTemplate( + "tpl.table_row_wiki_page.html", + "Modules/Wiki" + ); + break; + } + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->getPages(); + + $this->setShowRowsSelector(true); + + switch ($this->pg_list_mode) { + case IL_WIKI_WHAT_LINKS_HERE: + $this->setTitle(sprintf( + $lng->txt("wiki_what_links_to_page"), + ilWikiPage::lookupTitle($this->page_id) + )); + break; + + default: + $this->setTitle($lng->txt("wiki_" . $a_mode . "_pages")); + break; + } + } + + /** + * Get pages for list. + */ + public function getPages() + { + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + + $pages = array(); + $this->setDefaultOrderField("title"); + + switch ($this->pg_list_mode) { + case IL_WIKI_WHAT_LINKS_HERE: + $pages = ilWikiPage::getLinksToPage($this->wiki_id, $this->page_id); + break; + + case IL_WIKI_ALL_PAGES: + $pages = ilWikiPage::getAllWikiPages($this->wiki_id); + break; + + case IL_WIKI_NEW_PAGES: + $this->setDefaultOrderField("created"); + $this->setDefaultOrderDirection("desc"); + $pages = ilWikiPage::getNewWikiPages($this->wiki_id); + break; + + case IL_WIKI_POPULAR_PAGES: + $this->setDefaultOrderField("cnt"); + $this->setDefaultOrderDirection("desc"); + $pages = ilWikiPage::getPopularPages($this->wiki_id); + break; + + case IL_WIKI_ORPHANED_PAGES: + $pages = ilWikiPage::getOrphanedPages($this->wiki_id); + break; + } + + if ($pages) { + // enable sorting + include_once("./Services/User/classes/class.ilUserUtil.php"); + foreach (array_keys($pages) as $idx) { + $pages[$idx]["user_sort"] = ilUserUtil::getNamePresentation($pages[$idx]["user"], false, false); + } + } + + $this->setData($pages); + } + + public function numericOrdering($a_field) + { + if ($a_field == "cnt") { + return true; + } + return false; + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + if ($this->pg_list_mode == IL_WIKI_NEW_PAGES) { + $this->tpl->setVariable("TXT_PAGE_TITLE", $a_set["title"]); + $this->tpl->setVariable( + "DATE", + ilDatePresentation::formatDate(new ilDateTime($a_set["created"], IL_CAL_DATETIME)) + ); + } elseif ($this->pg_list_mode == IL_WIKI_POPULAR_PAGES) { + $this->tpl->setVariable("TXT_PAGE_TITLE", $a_set["title"]); + $this->tpl->setVariable("HITS", $a_set["cnt"]); + } else { + $this->tpl->setVariable("TXT_PAGE_TITLE", $a_set["title"]); + $this->tpl->setVariable( + "DATE", + ilDatePresentation::formatDate(new ilDateTime($a_set["date"], IL_CAL_DATETIME)) + ); + } + $this->tpl->setVariable( + "HREF_PAGE", + ilObjWikiGUI::getGotoLink($_GET["ref_id"], $a_set["title"]) + ); + + // user name + include_once("./Services/User/classes/class.ilUserUtil.php"); + $this->tpl->setVariable( + "TXT_USER", + ilUserUtil::getNamePresentation( + $a_set["user"], + true, + true, + $ilCtrl->getLinkTarget($this->getParentObject(), $this->getParentCmd()) + ) + ); + } } -?> diff --git a/Modules/Wiki/classes/class.ilWikiPerm.php b/Modules/Wiki/classes/class.ilWikiPerm.php index e0295847ee62770cf9249fb99b2c4b0e5632c89b..5bd8ef497d50244a8f23d5cd515492f1352ce349 100644 --- a/Modules/Wiki/classes/class.ilWikiPerm.php +++ b/Modules/Wiki/classes/class.ilWikiPerm.php @@ -11,36 +11,32 @@ */ class ilWikiPerm { - /** - * Check permission - * - * @param string $a_perm permission - * @param int $a_ref_id ref id - * @return bool true/false - */ - static function check($a_perm, $a_ref_id, $a_cmd = "") - { - global $DIC; - - $ilAccess = $DIC->access(); - switch ($a_perm) - { - case "edit_wiki_navigation": - return ($ilAccess->checkAccess("write", "", $a_ref_id) - || $ilAccess->checkAccess("edit_wiki_navigation", "", $a_ref_id)); - case "delete_wiki_pages": - return ($ilAccess->checkAccess("write", "", $a_ref_id) - || $ilAccess->checkAccess("delete_wiki_pages", "", $a_ref_id)); - case "activate_wiki_protection": - return ($ilAccess->checkAccess("write", "", $a_ref_id) - || $ilAccess->checkAccess("activate_wiki_protection", "", $a_ref_id)); - case "wiki_html_export": - return ($ilAccess->checkAccess("write", "", $a_ref_id) - || $ilAccess->checkAccess("wiki_html_export", "", $a_ref_id)); - } - return $ilAccess->checkAccess($a_perm, $a_cmd, $a_ref_id); - } + /** + * Check permission + * + * @param string $a_perm permission + * @param int $a_ref_id ref id + * @return bool true/false + */ + public static function check($a_perm, $a_ref_id, $a_cmd = "") + { + global $DIC; + $ilAccess = $DIC->access(); + switch ($a_perm) { + case "edit_wiki_navigation": + return ($ilAccess->checkAccess("write", "", $a_ref_id) + || $ilAccess->checkAccess("edit_wiki_navigation", "", $a_ref_id)); + case "delete_wiki_pages": + return ($ilAccess->checkAccess("write", "", $a_ref_id) + || $ilAccess->checkAccess("delete_wiki_pages", "", $a_ref_id)); + case "activate_wiki_protection": + return ($ilAccess->checkAccess("write", "", $a_ref_id) + || $ilAccess->checkAccess("activate_wiki_protection", "", $a_ref_id)); + case "wiki_html_export": + return ($ilAccess->checkAccess("write", "", $a_ref_id) + || $ilAccess->checkAccess("wiki_html_export", "", $a_ref_id)); + } + return $ilAccess->checkAccess($a_perm, $a_cmd, $a_ref_id); + } } - -?> \ No newline at end of file diff --git a/Modules/Wiki/classes/class.ilWikiRecentChangesTableGUI.php b/Modules/Wiki/classes/class.ilWikiRecentChangesTableGUI.php index 9000c05b0cbd135a56288b01b799bb429bacd9dd..e6ab3ff9e452071fee5ee6416ddb62d1cf6ed964 100755 --- a/Modules/Wiki/classes/class.ilWikiRecentChangesTableGUI.php +++ b/Modules/Wiki/classes/class.ilWikiRecentChangesTableGUI.php @@ -1,24 +1,24 @@ ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->wiki_id = $a_wiki_id; + + $this->addColumn($lng->txt("wiki_last_changed"), "", "33%"); + $this->addColumn($lng->txt("wiki_page"), "", "33%"); + $this->addColumn($lng->txt("wiki_last_changed_by"), "", "67%"); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate( + "tpl.table_row_recent_changes.html", + "Modules/Wiki" + ); + $this->getRecentChanges(); + + $this->setShowRowsSelector(true); + + $this->setTitle($lng->txt("wiki_recent_changes")); + } + + /** + * Get pages for list. + */ + public function getRecentChanges() + { + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $changes = ilWikiPage::getRecentChanges("wpg", $this->wiki_id); + $this->setDefaultOrderField("date"); + $this->setDefaultOrderDirection("desc"); + $this->setData($changes); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->wiki_id = $a_wiki_id; - - $this->addColumn($lng->txt("wiki_last_changed"), "", "33%"); - $this->addColumn($lng->txt("wiki_page"), "", "33%"); - $this->addColumn($lng->txt("wiki_last_changed_by"), "", "67%"); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.table_row_recent_changes.html", - "Modules/Wiki"); - $this->getRecentChanges(); - - $this->setShowRowsSelector(true); - - $this->setTitle($lng->txt("wiki_recent_changes")); - } - - /** - * Get pages for list. - */ - function getRecentChanges() - { - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $changes = ilWikiPage::getRecentChanges("wpg", $this->wiki_id); - $this->setDefaultOrderField("date"); - $this->setDefaultOrderDirection("desc"); - $this->setData($changes); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $title = ilWikiPage::lookupTitle($a_set["id"]); - $this->tpl->setVariable("TXT_PAGE_TITLE", $title); - $this->tpl->setVariable("DATE", - ilDatePresentation::formatDate(new ilDateTime($a_set["date"], IL_CAL_DATETIME))); - $ilCtrl->setParameterByClass("ilwikipagegui", "page", rawurlencode($title)); - $ilCtrl->setParameterByClass("ilwikipagegui", "old_nr", $a_set["nr"]); - $this->tpl->setVariable("HREF_PAGE", - $ilCtrl->getLinkTargetByClass("ilwikipagegui", "preview")); - - // user name - include_once("./Services/User/classes/class.ilUserUtil.php"); - $this->tpl->setVariable("TXT_USER", - ilUserUtil::getNamePresentation($a_set["user"], true, true, - $ilCtrl->getLinkTarget($this->getParentObject(), $this->getParentCmd()) - )); - } + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $title = ilWikiPage::lookupTitle($a_set["id"]); + $this->tpl->setVariable("TXT_PAGE_TITLE", $title); + $this->tpl->setVariable( + "DATE", + ilDatePresentation::formatDate(new ilDateTime($a_set["date"], IL_CAL_DATETIME)) + ); + $ilCtrl->setParameterByClass("ilwikipagegui", "page", rawurlencode($title)); + $ilCtrl->setParameterByClass("ilwikipagegui", "old_nr", $a_set["nr"]); + $this->tpl->setVariable( + "HREF_PAGE", + $ilCtrl->getLinkTargetByClass("ilwikipagegui", "preview") + ); + // user name + include_once("./Services/User/classes/class.ilUserUtil.php"); + $this->tpl->setVariable( + "TXT_USER", + ilUserUtil::getNamePresentation( + $a_set["user"], + true, + true, + $ilCtrl->getLinkTarget($this->getParentObject(), $this->getParentCmd()) + ) + ); + } } -?> diff --git a/Modules/Wiki/classes/class.ilWikiSearchBlockGUI.php b/Modules/Wiki/classes/class.ilWikiSearchBlockGUI.php index 1fdcc9a893794a500510234586b9a5d37d7973f1..61747981ab48110a07238d1536d94a2da6bb7b0d 100755 --- a/Modules/Wiki/classes/class.ilWikiSearchBlockGUI.php +++ b/Modules/Wiki/classes/class.ilWikiSearchBlockGUI.php @@ -1,24 +1,24 @@ ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->access = $DIC->access(); - $lng = $DIC->language(); - - parent::__construct(); - - $lng->loadLanguageModule("wiki"); - $this->setEnableNumInfo(false); - - $this->setTitle($lng->txt("wiki_wiki_search")); - $this->allow_moving = false; - } + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->access = $DIC->access(); + $lng = $DIC->language(); + + parent::__construct(); + + $lng->loadLanguageModule("wiki"); + $this->setEnableNumInfo(false); + + $this->setTitle($lng->txt("wiki_wiki_search")); + $this->allow_moving = false; + } - /** - * @inheritdoc - */ - public function getBlockType() : string - { - return self::$block_type; - } + /** + * @inheritdoc + */ + public function getBlockType() : string + { + return self::$block_type; + } - /** - * @inheritdoc - */ - protected function isRepositoryObject(): bool - { - return false; - } - - /** - * Get Screen Mode for current command. - */ - static function getScreenMode() - { - return IL_SCREEN_SIDE; - } + /** + * @inheritdoc + */ + protected function isRepositoryObject() : bool + { + return false; + } + + /** + * Get Screen Mode for current command. + */ + public static function getScreenMode() + { + return IL_SCREEN_SIDE; + } - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; - $next_class = $ilCtrl->getNextClass(); - $cmd = $ilCtrl->getCmd("getHTML"); + $next_class = $ilCtrl->getNextClass(); + $cmd = $ilCtrl->getCmd("getHTML"); - switch ($next_class) - { - default: - return $this->$cmd(); - } - } + switch ($next_class) { + default: + return $this->$cmd(); + } + } - /** - * Get bloch HTML code. - */ - function getHTML() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - return parent::getHTML(); - } + /** + * Get bloch HTML code. + */ + public function getHTML() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + return parent::getHTML(); + } - /** - * Fill data section - */ - function fillDataSection() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilAccess = $this->access; - - $tpl = new ilTemplate("tpl.wiki_search_block.html", true, true, "Modules/Wiki"); - - // go - $tpl->setVariable("TXT_PERFORM", $lng->txt("wiki_search")); - $tpl->setVariable("FORMACTION", - $ilCtrl->getFormActionByClass("ilobjwikigui", "performSearch")); - $tpl->setVariable("SEARCH_TERM", - ilUtil::prepareFormOutput(ilUtil::stripSlashes($_POST["search_term"]))); + /** + * Fill data section + */ + public function fillDataSection() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilAccess = $this->access; + + $tpl = new ilTemplate("tpl.wiki_search_block.html", true, true, "Modules/Wiki"); + + // go + $tpl->setVariable("TXT_PERFORM", $lng->txt("wiki_search")); + $tpl->setVariable( + "FORMACTION", + $ilCtrl->getFormActionByClass("ilobjwikigui", "performSearch") + ); + $tpl->setVariable( + "SEARCH_TERM", + ilUtil::prepareFormOutput(ilUtil::stripSlashes($_POST["search_term"])) + ); - $this->setDataSection($tpl->get()); - } + $this->setDataSection($tpl->get()); + } } - -?> diff --git a/Modules/Wiki/classes/class.ilWikiSearchResultsTableGUI.php b/Modules/Wiki/classes/class.ilWikiSearchResultsTableGUI.php index bc11060930f5f8b9073351efced5ba31ad595202..7959325a63d8e58cc32df6695faa9d2b1df6528e 100755 --- a/Modules/Wiki/classes/class.ilWikiSearchResultsTableGUI.php +++ b/Modules/Wiki/classes/class.ilWikiSearchResultsTableGUI.php @@ -1,24 +1,24 @@ ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $ilCtrl = $DIC->ctrl(); - $lng = $DIC->language(); - - parent::__construct($a_parent_obj, $a_parent_cmd); - $this->wiki_id = $a_wiki_id; - - $this->addColumn($lng->txt("wiki_page"), "", "100%"); - $this->setEnableHeader(true); - $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); - $this->setRowTemplate("tpl.search_result.html", - "Modules/Wiki"); - - $this->setData($a_results); - $this->setLimit(0); - - $this->setTitle($lng->txt("wiki_search_results").' "'.str_replace(array('"'), "", $a_term).'"'); - } - - /** - * Standard Version of Fill Row. Most likely to - * be overwritten by derived class. - */ - protected function fillRow($a_set) - { - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); - $title = ilWikiPage::lookupTitle($a_set["page_id"]); - $this->tpl->setVariable("TXT_PAGE_TITLE", $title); - $ilCtrl->setParameterByClass("ilwikipagegui", "page", - ilWikiUtil::makeUrlTitle($title)); - $this->tpl->setVariable("HREF_PAGE", - $ilCtrl->getLinkTargetByClass("ilwikipagegui", "preview")); - } + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $ilCtrl = $DIC->ctrl(); + $lng = $DIC->language(); + + parent::__construct($a_parent_obj, $a_parent_cmd); + $this->wiki_id = $a_wiki_id; + + $this->addColumn($lng->txt("wiki_page"), "", "100%"); + $this->setEnableHeader(true); + $this->setFormAction($ilCtrl->getFormAction($a_parent_obj)); + $this->setRowTemplate( + "tpl.search_result.html", + "Modules/Wiki" + ); + + $this->setData($a_results); + $this->setLimit(0); + + $this->setTitle($lng->txt("wiki_search_results") . ' "' . str_replace(array('"'), "", $a_term) . '"'); + } + + /** + * Standard Version of Fill Row. Most likely to + * be overwritten by derived class. + */ + protected function fillRow($a_set) + { + $lng = $this->lng; + $ilCtrl = $this->ctrl; + include_once("./Modules/Wiki/classes/class.ilWikiPage.php"); + $title = ilWikiPage::lookupTitle($a_set["page_id"]); + $this->tpl->setVariable("TXT_PAGE_TITLE", $title); + $ilCtrl->setParameterByClass( + "ilwikipagegui", + "page", + ilWikiUtil::makeUrlTitle($title) + ); + $this->tpl->setVariable( + "HREF_PAGE", + $ilCtrl->getLinkTargetByClass("ilwikipagegui", "preview") + ); + } } -?> diff --git a/Modules/Wiki/classes/class.ilWikiSideBlockGUI.php b/Modules/Wiki/classes/class.ilWikiSideBlockGUI.php index 6d2d57ce2af7d17b88a1c416b5c9b2960665b051..28a34df96670399cb22aa7f0c50f99896cb31b2d 100755 --- a/Modules/Wiki/classes/class.ilWikiSideBlockGUI.php +++ b/Modules/Wiki/classes/class.ilWikiSideBlockGUI.php @@ -13,165 +13,161 @@ include_once("Services/Block/classes/class.ilBlockGUI.php"); */ class ilWikiSideBlockGUI extends ilBlockGUI { - static $block_type = "wikiside"; - static $st_data; - - /** - * Constructor - */ - function __construct() - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - $this->user = $DIC->user(); - $this->access = $DIC->access(); - $lng = $DIC->language(); - - parent::__construct(); - - $lng->loadLanguageModule("wiki"); - $this->setEnableNumInfo(false); - - $this->setTitle($lng->txt("wiki_quick_navigation")); - $this->allow_moving = false; - } - - /** - * @inheritdoc - */ - public function getBlockType(): string - { - return self::$block_type; - } - - /** - * @inheritdoc - */ - protected function isRepositoryObject(): bool - { - return false; - } - - /** - * Get Screen Mode for current command. - */ - static function getScreenMode() - { - return IL_SCREEN_SIDE; - } - - /** - * execute command - */ - function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass(); - $cmd = $ilCtrl->getCmd("getHTML"); - - switch ($next_class) - { - default: - return $this->$cmd(); - } - } - - /** - * Set Page Object - * - * @param int $a_pageob Page Object - */ - function setPageObject($a_pageob) - { - $this->pageob = $a_pageob; - } - - /** - * Get Page Object - * - * @return int Page Object - */ - function getPageObject() - { - return $this->pageob; - } - - /** - * Get bloch HTML code. - */ - function getHTML() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilUser = $this->user; - - return parent::getHTML(); - } - - /** - * Fill data section - */ - function fillDataSection() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - $ilAccess = $this->access; - - $tpl = new ilTemplate("tpl.wiki_side_block_content.html", true, true, "Modules/Wiki"); - - $wp = $this->getPageObject(); - - // start page - $actions[] = array( - "txt" => $lng->txt("wiki_start_page"), - "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "gotoStartPage") - ); - - // all pages - $actions[] = array( - "txt" => $lng->txt("wiki_all_pages"), - "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "allPages") - ); - - // new pages - $actions[] = array( - "txt" => $lng->txt("wiki_new_pages"), - "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "newPages") - ); - - // popular pages - $actions[] = array( - "txt" => $lng->txt("wiki_popular_pages"), - "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "popularPages") - ); - - // orphaned pages - $actions[] = array( - "txt" => $lng->txt("wiki_orphaned_pages"), - "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "orphanedPages") - ); - - // recent changes - $actions[] = array( - "txt" => $lng->txt("wiki_recent_changes"), - "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "recentChanges") - ); - - foreach ($actions as $a) - { - $tpl->setCurrentBlock("action"); - $tpl->setVariable("HREF", $a["href"]); - $tpl->setVariable("TXT", $a["txt"]); - $tpl->parseCurrentBlock(); - - $tpl->touchBlock("item"); - } - - $this->setDataSection($tpl->get()); - } + public static $block_type = "wikiside"; + public static $st_data; + + /** + * Constructor + */ + public function __construct() + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + $this->user = $DIC->user(); + $this->access = $DIC->access(); + $lng = $DIC->language(); + + parent::__construct(); + + $lng->loadLanguageModule("wiki"); + $this->setEnableNumInfo(false); + + $this->setTitle($lng->txt("wiki_quick_navigation")); + $this->allow_moving = false; + } + + /** + * @inheritdoc + */ + public function getBlockType() : string + { + return self::$block_type; + } + + /** + * @inheritdoc + */ + protected function isRepositoryObject() : bool + { + return false; + } + + /** + * Get Screen Mode for current command. + */ + public static function getScreenMode() + { + return IL_SCREEN_SIDE; + } + + /** + * execute command + */ + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass(); + $cmd = $ilCtrl->getCmd("getHTML"); + + switch ($next_class) { + default: + return $this->$cmd(); + } + } + + /** + * Set Page Object + * + * @param int $a_pageob Page Object + */ + public function setPageObject($a_pageob) + { + $this->pageob = $a_pageob; + } + + /** + * Get Page Object + * + * @return int Page Object + */ + public function getPageObject() + { + return $this->pageob; + } + + /** + * Get bloch HTML code. + */ + public function getHTML() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilUser = $this->user; + + return parent::getHTML(); + } + + /** + * Fill data section + */ + public function fillDataSection() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + $ilAccess = $this->access; + + $tpl = new ilTemplate("tpl.wiki_side_block_content.html", true, true, "Modules/Wiki"); + + $wp = $this->getPageObject(); + + // start page + $actions[] = array( + "txt" => $lng->txt("wiki_start_page"), + "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "gotoStartPage") + ); + + // all pages + $actions[] = array( + "txt" => $lng->txt("wiki_all_pages"), + "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "allPages") + ); + + // new pages + $actions[] = array( + "txt" => $lng->txt("wiki_new_pages"), + "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "newPages") + ); + + // popular pages + $actions[] = array( + "txt" => $lng->txt("wiki_popular_pages"), + "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "popularPages") + ); + + // orphaned pages + $actions[] = array( + "txt" => $lng->txt("wiki_orphaned_pages"), + "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "orphanedPages") + ); + + // recent changes + $actions[] = array( + "txt" => $lng->txt("wiki_recent_changes"), + "href" => $ilCtrl->getLinkTargetByClass("ilobjwikigui", "recentChanges") + ); + + foreach ($actions as $a) { + $tpl->setCurrentBlock("action"); + $tpl->setVariable("HREF", $a["href"]); + $tpl->setVariable("TXT", $a["txt"]); + $tpl->parseCurrentBlock(); + + $tpl->touchBlock("item"); + } + + $this->setDataSection($tpl->get()); + } } - -?> diff --git a/Modules/Wiki/classes/class.ilWikiStat.php b/Modules/Wiki/classes/class.ilWikiStat.php index 42218bad67c442ac6f589d3b667c0f3032c87fea..b9100284a0c0c831941a47e3448539c12331dc40 100644 --- a/Modules/Wiki/classes/class.ilWikiStat.php +++ b/Modules/Wiki/classes/class.ilWikiStat.php @@ -24,7 +24,7 @@ * * (3) average rating ev: rating saved * [action: do (10), then for current records in wiki_stat_page: sum average rating / number of records where average rating is > 0] - * REVISION action: do (10), then build average rating from wiki page rating records NOT wiki_stat_page + * REVISION action: do (10), then build average rating from wiki page rating records NOT wiki_stat_page * * - wiki_stat_page pk: wiki_id, page_id, timestamp * @@ -80,1280 +80,1236 @@ */ class ilWikiStat { - const EVENT_PAGE_CREATED = 1; - const EVENT_PAGE_UPDATED = 2; - const EVENT_PAGE_READ = 3; - const EVENT_PAGE_DELETED = 4; - const EVENT_PAGE_RATING = 5; - - const KEY_FIGURE_WIKI_NUM_PAGES = 1; - const KEY_FIGURE_WIKI_NEW_PAGES = 2; - const KEY_FIGURE_WIKI_NEW_PAGES_AVG = 3; - const KEY_FIGURE_WIKI_EDIT_PAGES = 4; - const KEY_FIGURE_WIKI_EDIT_PAGES_AVG = 5; - const KEY_FIGURE_WIKI_DELETED_PAGES = 6; - const KEY_FIGURE_WIKI_READ_PAGES = 7; - const KEY_FIGURE_WIKI_USER_EDIT_PAGES = 8; - const KEY_FIGURE_WIKI_USER_EDIT_PAGES_AVG = 9; - const KEY_FIGURE_WIKI_NUM_RATING = 10; - const KEY_FIGURE_WIKI_NUM_RATING_AVG = 11; - const KEY_FIGURE_WIKI_RATING_AVG = 12; - const KEY_FIGURE_WIKI_INTERNAL_LINKS = 13; - const KEY_FIGURE_WIKI_INTERNAL_LINKS_AVG = 14; - const KEY_FIGURE_WIKI_EXTERNAL_LINKS = 15; - const KEY_FIGURE_WIKI_EXTERNAL_LINKS_AVG = 16; - const KEY_FIGURE_WIKI_WORDS = 17; - const KEY_FIGURE_WIKI_WORDS_AVG = 18; - const KEY_FIGURE_WIKI_CHARS = 19; - const KEY_FIGURE_WIKI_CHARS_AVG = 20; - const KEY_FIGURE_WIKI_FOOTNOTES = 21; - const KEY_FIGURE_WIKI_FOOTNOTES_AVG = 22; - - const KEY_FIGURE_WIKI_PAGE_CHANGES = 23; - const KEY_FIGURE_WIKI_PAGE_CHANGES_AVG = 24; - const KEY_FIGURE_WIKI_PAGE_USER_EDIT = 25; - const KEY_FIGURE_WIKI_PAGE_READ = 26; - const KEY_FIGURE_WIKI_PAGE_INTERNAL_LINKS = 27; - const KEY_FIGURE_WIKI_PAGE_EXTERNAL_LINKS = 28; - const KEY_FIGURE_WIKI_PAGE_WORDS = 29; - const KEY_FIGURE_WIKI_PAGE_CHARS = 30; - const KEY_FIGURE_WIKI_PAGE_FOOTNOTES = 31; - const KEY_FIGURE_WIKI_PAGE_RATINGS = 32; - - // - // WRITE - // - - /** - * Handle wiki page event - * - * @param int $a_event - * @param ilWikiPage $a_page_obj - * @param int $a_user_id - * @param int $a_additional_data - */ - public static function handleEvent($a_event, ilWikiPage $a_page_obj, $a_user_id = null, array $a_additional_data = null) - { - global $DIC; + const EVENT_PAGE_CREATED = 1; + const EVENT_PAGE_UPDATED = 2; + const EVENT_PAGE_READ = 3; + const EVENT_PAGE_DELETED = 4; + const EVENT_PAGE_RATING = 5; + + const KEY_FIGURE_WIKI_NUM_PAGES = 1; + const KEY_FIGURE_WIKI_NEW_PAGES = 2; + const KEY_FIGURE_WIKI_NEW_PAGES_AVG = 3; + const KEY_FIGURE_WIKI_EDIT_PAGES = 4; + const KEY_FIGURE_WIKI_EDIT_PAGES_AVG = 5; + const KEY_FIGURE_WIKI_DELETED_PAGES = 6; + const KEY_FIGURE_WIKI_READ_PAGES = 7; + const KEY_FIGURE_WIKI_USER_EDIT_PAGES = 8; + const KEY_FIGURE_WIKI_USER_EDIT_PAGES_AVG = 9; + const KEY_FIGURE_WIKI_NUM_RATING = 10; + const KEY_FIGURE_WIKI_NUM_RATING_AVG = 11; + const KEY_FIGURE_WIKI_RATING_AVG = 12; + const KEY_FIGURE_WIKI_INTERNAL_LINKS = 13; + const KEY_FIGURE_WIKI_INTERNAL_LINKS_AVG = 14; + const KEY_FIGURE_WIKI_EXTERNAL_LINKS = 15; + const KEY_FIGURE_WIKI_EXTERNAL_LINKS_AVG = 16; + const KEY_FIGURE_WIKI_WORDS = 17; + const KEY_FIGURE_WIKI_WORDS_AVG = 18; + const KEY_FIGURE_WIKI_CHARS = 19; + const KEY_FIGURE_WIKI_CHARS_AVG = 20; + const KEY_FIGURE_WIKI_FOOTNOTES = 21; + const KEY_FIGURE_WIKI_FOOTNOTES_AVG = 22; + + const KEY_FIGURE_WIKI_PAGE_CHANGES = 23; + const KEY_FIGURE_WIKI_PAGE_CHANGES_AVG = 24; + const KEY_FIGURE_WIKI_PAGE_USER_EDIT = 25; + const KEY_FIGURE_WIKI_PAGE_READ = 26; + const KEY_FIGURE_WIKI_PAGE_INTERNAL_LINKS = 27; + const KEY_FIGURE_WIKI_PAGE_EXTERNAL_LINKS = 28; + const KEY_FIGURE_WIKI_PAGE_WORDS = 29; + const KEY_FIGURE_WIKI_PAGE_CHARS = 30; + const KEY_FIGURE_WIKI_PAGE_FOOTNOTES = 31; + const KEY_FIGURE_WIKI_PAGE_RATINGS = 32; + + // + // WRITE + // + + /** + * Handle wiki page event + * + * @param int $a_event + * @param ilWikiPage $a_page_obj + * @param int $a_user_id + * @param int $a_additional_data + */ + public static function handleEvent($a_event, ilWikiPage $a_page_obj, $a_user_id = null, array $a_additional_data = null) + { + global $DIC; - $ilUser = $DIC->user(); - - if(!$a_user_id) - { - $a_user_id = $ilUser->getId(); - } - if(!$a_user_id || $a_user_id == ANONYMOUS_USER_ID) - { - return; - } - - switch((int)$a_event) - { - case self::EVENT_PAGE_CREATED: - self::handlePageCreated($a_page_obj, $a_user_id); - break; - - case self::EVENT_PAGE_UPDATED: - self::handlePageUpdated($a_page_obj, $a_user_id, $a_additional_data); - break; - - case self::EVENT_PAGE_READ: - self::handlePageRead($a_page_obj, $a_user_id); - break; - - case self::EVENT_PAGE_DELETED: - self::handlePageDeletion($a_page_obj, $a_user_id); - break; - - case self::EVENT_PAGE_RATING: - self::handlePageRating($a_page_obj, $a_user_id); - break; - - default: - return; - } - } - - /** - * Get current time frame (hourly) - * - * @return string - */ - protected static function getTimestamp() - { - return date("Y-m-d H:00:00"); - } - - /** - * Write data to DB - * - * - Handles update/insert depending on time frame - * - supports increment/decrement custom values - * - * @param string $a_table - * @param array $a_primary - * @param array $a_values - */ - protected static function writeData($a_table, array $a_primary, array $a_values) - { - global $DIC; + $ilUser = $DIC->user(); + + if (!$a_user_id) { + $a_user_id = $ilUser->getId(); + } + if (!$a_user_id || $a_user_id == ANONYMOUS_USER_ID) { + return; + } + + switch ((int) $a_event) { + case self::EVENT_PAGE_CREATED: + self::handlePageCreated($a_page_obj, $a_user_id); + break; + + case self::EVENT_PAGE_UPDATED: + self::handlePageUpdated($a_page_obj, $a_user_id, $a_additional_data); + break; + + case self::EVENT_PAGE_READ: + self::handlePageRead($a_page_obj, $a_user_id); + break; + + case self::EVENT_PAGE_DELETED: + self::handlePageDeletion($a_page_obj, $a_user_id); + break; + + case self::EVENT_PAGE_RATING: + self::handlePageRating($a_page_obj, $a_user_id); + break; + + default: + return; + } + } + + /** + * Get current time frame (hourly) + * + * @return string + */ + protected static function getTimestamp() + { + return date("Y-m-d H:00:00"); + } + + /** + * Write data to DB + * + * - Handles update/insert depending on time frame + * - supports increment/decrement custom values + * + * @param string $a_table + * @param array $a_primary + * @param array $a_values + */ + protected static function writeData($a_table, array $a_primary, array $a_values) + { + global $DIC; - $ilDB = $DIC->database(); - - $tstamp = self::getTimestamp(); - $a_primary["ts"] = array("timestamp", $tstamp); + $ilDB = $DIC->database(); + + $tstamp = self::getTimestamp(); + $a_primary["ts"] = array("timestamp", $tstamp); - $ilAtomQuery = $ilDB->buildAtomQuery(); - $ilAtomQuery->addTableLock($a_table); + $ilAtomQuery = $ilDB->buildAtomQuery(); + $ilAtomQuery->addTableLock($a_table); - $ilAtomQuery->addQueryCallable( - function(ilDBInterface $ilDB) use($a_table, $a_primary, $a_values, $tstamp, &$is_update){ + $ilAtomQuery->addQueryCallable( + function (ilDBInterface $ilDB) use ($a_table, $a_primary, $a_values, $tstamp, &$is_update) { + $primary = array(); + foreach ($a_primary as $column => $value) { + $primary[] = $column . " = " . $ilDB->quote($value[1], $value[0]); + } + $primary = implode(" AND ", $primary); - $primary = array(); - foreach($a_primary as $column => $value) - { - $primary[] = $column." = ".$ilDB->quote($value[1], $value[0]); - } - $primary = implode(" AND ", $primary); + $set = $ilDB->query("SELECT ts FROM " . $a_table . + " WHERE " . $primary); - $set = $ilDB->query("SELECT ts FROM ".$a_table. - " WHERE ".$primary); + $is_update = (bool) $ilDB->numRows($set); - $is_update = (bool)$ilDB->numRows($set); + // update (current timeframe) + if ($is_update) { + $values = array(); + foreach ($a_values as $column => $value) { + if ($value[0] == "increment") { + $values[] = $column . " = " . $column . "+1"; + } elseif ($value[0] == "decrement") { + $values[] = $column . " = " . $column . "-1"; + } else { + $values[] = $column . " = " . $ilDB->quote($value[1], $value[0]); + } + } + $values = implode(", ", $values); - // update (current timeframe) - if($is_update) - { - $values = array(); - foreach($a_values as $column => $value) - { - if($value[0] == "increment") - { - $values[] = $column." = ".$column."+1"; - } - else if($value[0] == "decrement") - { - $values[] = $column." = ".$column."-1"; - } - else - { - $values[] = $column." = ".$ilDB->quote($value[1], $value[0]); - } - } - $values = implode(", ", $values); + $sql = "UPDATE " . $a_table . + " SET " . $values . + " WHERE " . $primary; + } + // insert (no entry yet for current time frame) + else { + $a_values = array_merge($a_primary, $a_values); + $a_values["ts_day"] = array("text", substr($tstamp, 0, 10)); + $a_values["ts_hour"] = array("integer", (int) substr($tstamp, 11, 2)); - $sql = "UPDATE ".$a_table. - " SET ".$values. - " WHERE ".$primary; - } - // insert (no entry yet for current time frame) - else - { - $a_values = array_merge($a_primary, $a_values); - $a_values["ts_day"] = array("text", substr($tstamp, 0, 10)); - $a_values["ts_hour"] = array("integer", (int)substr($tstamp, 11, 2)); + $values = array(); + foreach ($a_values as $column => $value) { + $columns[] = $column; + if ($value[0] == "increment") { + $value[0] = "integer"; + } elseif ($value[0] == "decrement") { + $value[0] = "integer"; + $value[1] = 0; + } + $values[] = $ilDB->quote($value[1], $value[0]); + } + $values = implode(", ", $values); + $columns = implode(", ", $columns); - $values = array(); - foreach($a_values as $column => $value) - { - $columns[] = $column; - if($value[0] == "increment") - { - $value[0] = "integer"; - } - else if($value[0] == "decrement") - { - $value[0] = "integer"; - $value[1] = 0; - } - $values[] = $ilDB->quote($value[1], $value[0]); - } - $values = implode(", ", $values); - $columns = implode(", ", $columns); + $sql = "INSERT INTO " . $a_table . + " (" . $columns . ")" . + " VALUES (" . $values . ")"; + } + $ilDB->manipulate($sql); + } + ); + $ilAtomQuery->run(); + + return $is_update; + } + + /** + * Write data to wiki_stat + * + * @param int $a_wiki_id + * @param array $a_values + */ + protected static function writeStat($a_wiki_id, $a_values) + { + $primary = array( + "wiki_id" => array("integer", $a_wiki_id) + ); + self::writeData("wiki_stat", $primary, $a_values); + } + + /** + * Write data to wiki_stat_page + * + * @param int $a_wiki_id + * @param int $a_page_id + * @param array $a_values + */ + protected static function writeStatPage($a_wiki_id, $a_page_id, $a_values) + { + $primary = array( + "wiki_id" => array("integer", $a_wiki_id), + "page_id" => array("integer", $a_page_id), + ); + self::writeData("wiki_stat_page", $primary, $a_values); + } + + /** + * Write data to wiki_stat_page_user + * + * @param int $a_wiki_id + * @param int $a_page_id + * @param int $a_user_id + * @param array $a_values + */ + protected static function writeStatPageUser($a_wiki_id, $a_page_id, $a_user_id, $a_values) + { + $primary = array( + "wiki_id" => array("integer", $a_wiki_id), + "page_id" => array("integer", $a_page_id), + "user_id" => array("integer", $a_user_id) + ); + self::writeData("wiki_stat_page_user", $primary, $a_values); + } + + /** + * Write to wiki_stat_user + * + * @param int $a_wiki_id + * @param int $a_user_id + * @param array $a_values + */ + protected static function writeStatUser($a_wiki_id, $a_user_id, $a_values) + { + $primary = array( + "wiki_id" => array("integer", $a_wiki_id), + "user_id" => array("integer", $a_user_id) + ); + self::writeData("wiki_stat_user", $primary, $a_values); + } + + /** + * Count pages in wiki + * + * @param int $a_wiki_id + * @return int + */ + protected static function countPages($a_wiki_id) + { + return sizeof(ilWikiPage::getAllWikiPages($a_wiki_id)); + } + + /** + * Get average rating for wiki or wiki page + * + * @param int $a_wiki_id + * @param int $a_page_id + * @return array + */ + protected static function getAverageRating($a_wiki_id, $a_page_id = null) + { + include_once "Services/Rating/classes/class.ilRating.php"; + + if (!$a_page_id) { + return ilRating::getOverallRatingForObject( + $a_wiki_id, + "wiki" + ); + } else { + return ilRating::getOverallRatingForObject( + $a_wiki_id, + "wiki", + $a_page_id, + "wpg" + ); + } + } + + /** + * Handle wiki page creation + * + * @param ilWikiPage $a_page_obj + * @param int $a_user_id + */ + public static function handlePageCreated(ilWikiPage $a_page_obj, $a_user_id) + { + // wiki: num_pages (count) + self::writeStat( + $a_page_obj->getWikiId(), + array( + "num_pages" => array("integer", self::countPages($a_page_obj->getWikiId())), + "del_pages" => array("integer", 0), + "avg_rating" => array("integer", 0) + ) + ); + + // user: new_pages+1 + self::writeStatUser( + $a_page_obj->getWikiId(), + $a_user_id, + array( + "new_pages" => array("increment", 1) + ) + ); + } + + /** + * Handle wiki page update + * + * @param ilWikiPage $a_page_obj + * @param int $a_user_id + * @param array $a_page_data + */ + public static function handlePageUpdated(ilWikiPage $a_page_obj, $a_user_id, array $a_page_data = null) + { + // page_user: changes+1 + self::writeStatPageUser( + $a_page_obj->getWikiId(), + $a_page_obj->getId(), + $a_user_id, + array( + "changes" => array("increment", 1) + ) + ); + + // page: see ilWikiPage::afterUpdate() + $values = array( + "int_links" => array("integer", $a_page_data["int_links"]), + "ext_links" => array("integer", $a_page_data["ext_links"]), + "footnotes" => array("integer", $a_page_data["footnotes"]), + "num_words" => array("integer", $a_page_data["num_words"]), + "num_chars" => array("integer", $a_page_data["num_chars"]), + "num_ratings" => array("integer", 0), + "avg_rating" => array("integer", 0) + ); + self::writeStatPage($a_page_obj->getWikiId(), $a_page_obj->getId(), $values); + } + + /** + * Handle wiki page read + * + * @param ilWikiPage $a_page_obj + * @param int $a_user_id + */ + public static function handlePageRead(ilWikiPage $a_page_obj, $a_user_id) + { + // page_user: read_events+1 + self::writeStatPageUser( + $a_page_obj->getWikiId(), + $a_page_obj->getId(), + $a_user_id, + array( + "read_events" => array("increment", 1) + ) + ); + } + + /** + * Handle wiki page deletion + * + * @param ilWikiPage $a_page_obj + * @param int $a_user_id + */ + public static function handlePageDeletion(ilWikiPage $a_page_obj, $a_user_id) + { + global $DIC; - $sql = "INSERT INTO ".$a_table. - " (".$columns.")". - " VALUES (".$values.")"; - } - $ilDB->manipulate($sql); - }); - $ilAtomQuery->run(); - - return $is_update; - } - - /** - * Write data to wiki_stat - * - * @param int $a_wiki_id - * @param array $a_values - */ - protected static function writeStat($a_wiki_id, $a_values) - { - $primary = array( - "wiki_id" => array("integer", $a_wiki_id) - ); - self::writeData("wiki_stat", $primary, $a_values); - } - - /** - * Write data to wiki_stat_page - * - * @param int $a_wiki_id - * @param int $a_page_id - * @param array $a_values - */ - protected static function writeStatPage($a_wiki_id, $a_page_id, $a_values) - { - $primary = array( - "wiki_id" => array("integer", $a_wiki_id), - "page_id" => array("integer", $a_page_id), - ); - self::writeData("wiki_stat_page", $primary, $a_values); - } - - /** - * Write data to wiki_stat_page_user - * - * @param int $a_wiki_id - * @param int $a_page_id - * @param int $a_user_id - * @param array $a_values - */ - protected static function writeStatPageUser($a_wiki_id, $a_page_id, $a_user_id, $a_values) - { - $primary = array( - "wiki_id" => array("integer", $a_wiki_id), - "page_id" => array("integer", $a_page_id), - "user_id" => array("integer", $a_user_id) - ); - self::writeData("wiki_stat_page_user", $primary, $a_values); - } - - /** - * Write to wiki_stat_user - * - * @param int $a_wiki_id - * @param int $a_user_id - * @param array $a_values - */ - protected static function writeStatUser($a_wiki_id, $a_user_id, $a_values) - { - $primary = array( - "wiki_id" => array("integer", $a_wiki_id), - "user_id" => array("integer", $a_user_id) - ); - self::writeData("wiki_stat_user", $primary, $a_values); - } - - /** - * Count pages in wiki - * - * @param int $a_wiki_id - * @return int - */ - protected static function countPages($a_wiki_id) - { - return sizeof(ilWikiPage::getAllWikiPages($a_wiki_id)); - } - - /** - * Get average rating for wiki or wiki page - * - * @param int $a_wiki_id - * @param int $a_page_id - * @return array - */ - protected static function getAverageRating($a_wiki_id, $a_page_id = null) - { - include_once "Services/Rating/classes/class.ilRating.php"; - - if(!$a_page_id) - { - return ilRating::getOverallRatingForObject( - $a_wiki_id, - "wiki"); - } - else - { - return ilRating::getOverallRatingForObject( - $a_wiki_id, - "wiki", - $a_page_id, - "wpg"); - } - } - - /** - * Handle wiki page creation - * - * @param ilWikiPage $a_page_obj - * @param int $a_user_id - */ - public static function handlePageCreated(ilWikiPage $a_page_obj, $a_user_id) - { - // wiki: num_pages (count) - self::writeStat($a_page_obj->getWikiId(), - array( - "num_pages" => array("integer", self::countPages($a_page_obj->getWikiId())), - "del_pages" => array("integer", 0), - "avg_rating" => array("integer", 0) - )); - - // user: new_pages+1 - self::writeStatUser($a_page_obj->getWikiId(), $a_user_id, - array( - "new_pages" => array("increment", 1) - )); - } - - /** - * Handle wiki page update - * - * @param ilWikiPage $a_page_obj - * @param int $a_user_id - * @param array $a_page_data - */ - public static function handlePageUpdated(ilWikiPage $a_page_obj, $a_user_id, array $a_page_data = null) - { - // page_user: changes+1 - self::writeStatPageUser($a_page_obj->getWikiId(), $a_page_obj->getId(), $a_user_id, - array( - "changes" => array("increment", 1) - )); - - // page: see ilWikiPage::afterUpdate() - $values = array( - "int_links" => array("integer", $a_page_data["int_links"]), - "ext_links" => array("integer", $a_page_data["ext_links"]), - "footnotes" => array("integer", $a_page_data["footnotes"]), - "num_words" => array("integer", $a_page_data["num_words"]), - "num_chars" => array("integer", $a_page_data["num_chars"]), - "num_ratings" => array("integer", 0), - "avg_rating" => array("integer", 0) - ); - self::writeStatPage($a_page_obj->getWikiId(), $a_page_obj->getId(), $values); - } - - /** - * Handle wiki page read - * - * @param ilWikiPage $a_page_obj - * @param int $a_user_id - */ - public static function handlePageRead(ilWikiPage $a_page_obj, $a_user_id) - { - // page_user: read_events+1 - self::writeStatPageUser($a_page_obj->getWikiId(), $a_page_obj->getId(), $a_user_id, - array( - "read_events" => array("increment", 1) - )); - } - - /** - * Handle wiki page deletion - * - * @param ilWikiPage $a_page_obj - * @param int $a_user_id - */ - public static function handlePageDeletion(ilWikiPage $a_page_obj, $a_user_id) - { - global $DIC; + $ilDB = $DIC->database(); + + // copy last entry to have deletion timestamp + $sql = "SELECT * " . + " FROM wiki_stat_page" . + " WHERE wiki_id = " . $ilDB->quote($a_page_obj->getWikiId(), "integer") . + " AND page_id = " . $ilDB->quote($a_page_obj->getId(), "integer") . + " ORDER BY ts DESC"; + $ilDB->setLimit(1); + $set = $ilDB->query($sql); + + // #15748 + if ($ilDB->numRows($set)) { + $data = $ilDB->fetchAssoc($set); - $ilDB = $DIC->database(); - - // copy last entry to have deletion timestamp - $sql = "SELECT * ". - " FROM wiki_stat_page". - " WHERE wiki_id = ".$ilDB->quote($a_page_obj->getWikiId(), "integer"). - " AND page_id = ".$ilDB->quote($a_page_obj->getId(), "integer") . - " ORDER BY ts DESC"; - $ilDB->setLimit(1); - $set = $ilDB->query($sql); - - // #15748 - if($ilDB->numRows($set)) - { - $data = $ilDB->fetchAssoc($set); + // see self::handlePageUpdated() + $values = array( + "int_links" => array("integer", $data["int_links"]), + "ext_links" => array("integer", $data["ext_links"]), + "footnotes" => array("integer", $data["footnotes"]), + "num_words" => array("integer", $data["num_words"]), + "num_chars" => array("integer", $data["num_chars"]), + "num_ratings" => array("integer", $data["num_ratings"]), + "avg_rating" => array("integer", $data["avg_rating"]), + ); + self::writeStatPage((int) $a_page_obj->getWikiId(), $a_page_obj->getId(), $values); + } + + // mark all page entries as deleted + $ilDB->manipulate("UPDATE wiki_stat_page" . + " SET deleted = " . $ilDB->quote(1, "integer") . + " WHERE page_id = " . $ilDB->quote($a_page_obj->getId(), "integer") . + " AND wiki_id = " . $ilDB->quote($a_page_obj->getWikiId(), "integer")); + + // wiki: del_pages+1, num_pages (count), avg_rating + $rating = self::getAverageRating($a_page_obj->getWikiId()); + self::writeStat( + $a_page_obj->getWikiId(), + array( + "del_pages" => array("increment", 1), + "num_pages" => array("integer", self::countPages($a_page_obj->getWikiId())), + "avg_rating" => array("integer", $rating["avg"]*100) + ) + ); + } + + /** + * Handle wiki page rating + * + * @param ilWikiPage $a_page_obj + * @param int $a_user_id + */ + public static function handlePageRating(ilWikiPage $a_page_obj, $a_user_id) + { + // do page first! + $rating = self::getAverageRating($a_page_obj->getWikiId(), $a_page_obj->getId()); + + // wiki_stat_page: num_ratings, avg_rating + self::writeStatPage( + $a_page_obj->getWikiId(), + $a_page_obj->getId(), + array( + "num_ratings" => array("integer", $rating["cnt"]), + "avg_rating" => array("integer", $rating["avg"]*100), + ) + ); + + $rating = self::getAverageRating($a_page_obj->getWikiId()); + + // wiki_stat: avg_rating + $is_update = self::writeStat( + $a_page_obj->getWikiId(), + array( + "avg_rating" => array("integer", $rating["avg"]*100) + ) + ); + + if (!$is_update) { + // wiki: num_pages (count) + self::writeStat( + $a_page_obj->getWikiId(), + array( + "num_pages" => array("integer", self::countPages($a_page_obj->getWikiId())) + ) + ); + } + } + + + // + // READ HELPER + // - // see self::handlePageUpdated() - $values = array( - "int_links" => array("integer", $data["int_links"]), - "ext_links" => array("integer", $data["ext_links"]), - "footnotes" => array("integer", $data["footnotes"]), - "num_words" => array("integer", $data["num_words"]), - "num_chars" => array("integer", $data["num_chars"]), - "num_ratings" => array("integer", $data["num_ratings"]), - "avg_rating" => array("integer", $data["avg_rating"]), - ); - self::writeStatPage((int) $a_page_obj->getWikiId(), $a_page_obj->getId(), $values); - } - - // mark all page entries as deleted - $ilDB->manipulate("UPDATE wiki_stat_page". - " SET deleted = ".$ilDB->quote(1, "integer"). - " WHERE page_id = ".$ilDB->quote($a_page_obj->getId(), "integer"). - " AND wiki_id = ".$ilDB->quote($a_page_obj->getWikiId(), "integer")); - - // wiki: del_pages+1, num_pages (count), avg_rating - $rating = self::getAverageRating($a_page_obj->getWikiId()); - self::writeStat($a_page_obj->getWikiId(), - array( - "del_pages" => array("increment", 1), - "num_pages" => array("integer", self::countPages($a_page_obj->getWikiId())), - "avg_rating" => array("integer", $rating["avg"]*100) - )); - } - - /** - * Handle wiki page rating - * - * @param ilWikiPage $a_page_obj - * @param int $a_user_id - */ - public static function handlePageRating(ilWikiPage $a_page_obj, $a_user_id) - { - // do page first! - $rating = self::getAverageRating($a_page_obj->getWikiId(), $a_page_obj->getId()); - - // wiki_stat_page: num_ratings, avg_rating - self::writeStatPage($a_page_obj->getWikiId(), $a_page_obj->getId(), - array( - "num_ratings" => array("integer", $rating["cnt"]), - "avg_rating" => array("integer", $rating["avg"]*100), - )); - - $rating = self::getAverageRating($a_page_obj->getWikiId()); - - // wiki_stat: avg_rating - $is_update = self::writeStat($a_page_obj->getWikiId(), - array( - "avg_rating" => array("integer", $rating["avg"]*100) - )); - - if(!$is_update) - { - // wiki: num_pages (count) - self::writeStat($a_page_obj->getWikiId(), - array( - "num_pages" => array("integer", self::countPages($a_page_obj->getWikiId())) - )); - } - } - - - // - // READ HELPER - // + protected static function getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, $a_table, $a_field, $a_aggr_value, $a_sub_field = null, $a_sub_id = null, $a_build_full_period = false) + { + global $DIC; - protected static function getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, $a_table, $a_field, $a_aggr_value, $a_sub_field = null, $a_sub_id = null, $a_build_full_period = false) - { - global $DIC; + $ilDB = $DIC->database(); + + $res = array(); + $deleted = null; + + $sql = "SELECT ts_day, " . sprintf($a_aggr_value, $a_field) . " " . $a_field; + if ($a_table == "wiki_stat_page" && $a_sub_field) { + $sql .= ", MAX(deleted) deleted"; + } + $sql .= " FROM " . $a_table . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND ts_day >= " . $ilDB->quote($a_day_from, "text") . + " AND ts_day <= " . $ilDB->quote($a_day_to, "text"); + if (!$a_build_full_period) { + // to build full period data we need all values in DB + $sql .= " AND " . $a_field . " > " . $ilDB->quote(0, "integer") . + " AND " . $a_field . " IS NOT NULL"; + } + if ($a_sub_field) { + $sql .= " AND " . $a_sub_field . " = " . $ilDB->quote($a_sub_id, "integer"); + } + $sql .= " GROUP BY ts_day" . + " ORDER BY ts_day"; + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $res[$row["ts_day"]] = $row[$a_field]; + + $deleted = max($row["deleted"], $deleted); + } + + if ($a_build_full_period) { + $period_first = $a_day_from; + $period_last = $a_day_to; + + // check if sub was deleted in period + if ($a_table == "wiki_stat_page" && $a_sub_field && $deleted) { + $sql = "SELECT MAX(ts_day) last_day, MIN(ts_day) first_day" . + " FROM " . $a_table . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND " . $a_sub_field . " = " . $ilDB->quote($a_sub_id, "integer"); + $set = $ilDB->query($sql); + $row = $ilDB->fetchAssoc($set); + $last_day = $row["last_day"]; + if ($last_day < $period_last) { + $period_last = $last_day; + } + $first_day = $row["first_day"]; + if ($first_day > $period_first) { + $period_first = $first_day; + } + } + + $last_before_period = null; + if (!$res[$a_day_from]) { + $last_before_period = self::getWikiLast($a_wiki_id, $a_day_from, $a_table, $a_field, $a_sub_field, $a_sub_id); + } + + // no need to allow zero here as we are not building averages + self::buildFullPeriodData($res, $period_first, $period_last, $last_before_period); + } + + return $res; + } + + protected static function getWikiLast($a_wiki_id, $a_day_from, $a_table, $a_field, $a_sub_field = null, $a_sub_id = null) + { + global $DIC; - $ilDB = $DIC->database(); - - $res = array(); - $deleted = null; - - $sql = "SELECT ts_day, ".sprintf($a_aggr_value, $a_field)." ".$a_field; - if($a_table == "wiki_stat_page" && $a_sub_field) - { - $sql .= ", MAX(deleted) deleted"; - } - $sql .= " FROM ".$a_table. - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND ts_day >= ".$ilDB->quote($a_day_from, "text"). - " AND ts_day <= ".$ilDB->quote($a_day_to, "text"); - if(!$a_build_full_period) - { - // to build full period data we need all values in DB - $sql .= " AND ".$a_field." > ".$ilDB->quote(0, "integer"). - " AND ".$a_field." IS NOT NULL"; - } - if($a_sub_field) - { - $sql .= " AND ".$a_sub_field." = ".$ilDB->quote($a_sub_id, "integer"); - } - $sql .= " GROUP BY ts_day". - " ORDER BY ts_day"; - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $res[$row["ts_day"]] = $row[$a_field]; - - $deleted = max($row["deleted"], $deleted); - } - - if($a_build_full_period) - { - $period_first = $a_day_from; - $period_last = $a_day_to; - - // check if sub was deleted in period - if($a_table == "wiki_stat_page" && $a_sub_field && $deleted) - { - $sql = "SELECT MAX(ts_day) last_day, MIN(ts_day) first_day". - " FROM ".$a_table. - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND ".$a_sub_field." = ".$ilDB->quote($a_sub_id, "integer"); - $set = $ilDB->query($sql); - $row = $ilDB->fetchAssoc($set); - $last_day = $row["last_day"]; - if($last_day < $period_last) - { - $period_last = $last_day; - } - $first_day = $row["first_day"]; - if($first_day > $period_first) - { - $period_first = $first_day; - } - } - - $last_before_period = null; - if(!$res[$a_day_from]) - { - $last_before_period = self::getWikiLast($a_wiki_id, $a_day_from, $a_table, $a_field, $a_sub_field, $a_sub_id); - } - - // no need to allow zero here as we are not building averages - self::buildFullPeriodData($res, $period_first, $period_last, $last_before_period); - } - - return $res; - } - - protected static function getWikiLast($a_wiki_id, $a_day_from, $a_table, $a_field, $a_sub_field = null, $a_sub_id = null) - { - global $DIC; + $ilDB = $DIC->database(); + + // get last existing value before period (zero is valid) + $sql = "SELECT MAX(" . $a_field . ") latest" . + " FROM " . $a_table . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND ts_day < " . $ilDB->quote($a_day_from, "text"); + if ($a_sub_field) { + $sql .= " AND " . $a_sub_field . " = " . $ilDB->quote($a_sub_id, "integer"); + } + $sql .= " GROUP BY ts_day" . + " ORDER BY ts_day DESC"; + $ilDB->setLimit(1); + $set = $ilDB->query($sql); + $last_before_period = $ilDB->fetchAssoc($set); + return $last_before_period["latest"]; + } + + protected static function getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, $a_table, $a_field, $a_aggr_by, $a_aggr_value, $a_aggr_sub, $a_sub_field = null, $a_sub_id = null, $a_build_full_period = false) + { + global $DIC; - $ilDB = $DIC->database(); - - // get last existing value before period (zero is valid) - $sql = "SELECT MAX(".$a_field.") latest". - " FROM ".$a_table. - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND ts_day < ".$ilDB->quote($a_day_from, "text"); - if($a_sub_field) - { - $sql .= " AND ".$a_sub_field." = ".$ilDB->quote($a_sub_id, "integer"); - } - $sql .= " GROUP BY ts_day". - " ORDER BY ts_day DESC"; - $ilDB->setLimit(1); - $set = $ilDB->query($sql); - $last_before_period = $ilDB->fetchAssoc($set); - return $last_before_period["latest"]; - } - - protected static function getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, $a_table, $a_field, $a_aggr_by, $a_aggr_value, $a_aggr_sub, $a_sub_field = null, $a_sub_id = null, $a_build_full_period = false) - { - global $DIC; + $ilDB = $DIC->database(); + + $res = array(); + + if (!$a_build_full_period) { + $sql = "SELECT ts_day, " . sprintf($a_aggr_value, $a_field) . " " . $a_field . + " FROM (" . + // subquery to build average per $a_aggr_by + " SELECT ts_day, " . sprintf($a_aggr_sub, $a_field) . " " . $a_field . + " FROM " . $a_table . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND ts_day >= " . $ilDB->quote($a_day_from, "text") . + " AND ts_day <= " . $ilDB->quote($a_day_to, "text") . + " AND " . $a_field . " > " . $ilDB->quote(0, "integer") . + " AND " . $a_field . " IS NOT NULL"; + if ($a_sub_field) { + $sql .= " AND " . $a_sub_field . " = " . $ilDB->quote($a_sub_id, "integer"); + } + $sql .= " GROUP BY ts_day, " . $a_aggr_by . + ") aggr_sub" . + " GROUP BY ts_day" . + " ORDER BY ts_day"; + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $res[$row["ts_day"]] = $row[$a_field]; + } + } else { + $tmp = $all_aggr_ids = $deleted_in_period = $first_day_in_period = array(); + + if ($a_table != "wiki_stat_page") { + echo "can only build full period averages for wiki_stat_page"; + exit(); + } + + // as current period can be totally empty, gather existing subs + $sql = " SELECT *" . + " FROM (" . + " SELECT " . $a_aggr_by . ", MAX(deleted) deleted, MAX(ts_day) last_day, MIN(ts_day) first_day" . + " FROM " . $a_table . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " GROUP BY " . $a_aggr_by . + ") aggr_sub" . + " WHERE first_day <= " . $ilDB->quote($a_day_to, "text") . // not created after period + " AND (last_day >= " . $ilDB->quote($a_day_from, "text") . // (deleted in/after period + " OR deleted = " . $ilDB->quote(0, "integer") . ")"; // or still existing) + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $all_aggr_ids[] = $row[$a_aggr_by]; + + // if deleted in period we need the last day + if ($row["deleted"] && $row["last_day"] < $a_day_to) { + $deleted_in_period[$row[$a_aggr_by]] = $row["last_day"]; + } + // if created in period we need the first day + if ($row["first_day"] > $a_day_from) { + $first_day_in_period[$row[$a_aggr_by]] = $row["first_day"]; + } + } + + // we need to build average manually after completing period data (zero is valid) + $sql = " SELECT ts_day, " . $a_aggr_by . ", " . sprintf($a_aggr_sub, $a_field) . " " . $a_field . + " FROM " . $a_table . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND ts_day >= " . $ilDB->quote($a_day_from, "text") . + " AND ts_day <= " . $ilDB->quote($a_day_to, "text"); + $sql .= " GROUP BY ts_day, " . $a_aggr_by; + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + if (!in_array($row[$a_aggr_by], $all_aggr_ids)) { + var_dump("unexpected wiki_stat_page_entry", $row); + } + $tmp[$row[$a_aggr_by]][$row["ts_day"]] = $row[$a_field]; + } + + // build full period for each sub + foreach ($all_aggr_ids as $aggr_by_id) { + // last of entry of sub is before period + if (!is_array($tmp[$aggr_by_id])) { + $tmp[$aggr_by_id] = array(); + } + + // get last value before period to add missing entries in period + $last_before_period = null; + if (!$tmp[$aggr_by_id][$a_day_from]) { + $last_before_period = self::getWikiLast($a_wiki_id, $a_day_from, $a_table, $a_field, $a_aggr_by, $aggr_by_id); + } + + // if sub was created in period (see above), shorten period accordingly + $first_period_day = isset($first_day_in_period[$aggr_by_id]) + ? $first_day_in_period[$aggr_by_id] + : $a_day_from; + + // if sub was deleted in period (see above), shorten period accordingly + $last_period_day = isset($deleted_in_period[$aggr_by_id]) + ? $deleted_in_period[$aggr_by_id] + : $a_day_to; + + // allow zero as we need to correct number of valid subs per day (see below - AVG) + self::buildFullPeriodData($tmp[$aggr_by_id], $first_period_day, $last_period_day, $last_before_period, true); + + // distribute sub to days + foreach ($tmp[$aggr_by_id] as $day => $value) { + $res[$day][$aggr_by_id] = $value; + } + } + + // build average over subs + foreach ($res as $day => $values) { + switch ($a_aggr_value) { + case "AVG(%s)": + $res[$day] = array_sum($values)/sizeof($values); + break; + + case "SUM(%s)": + $res[$day] = array_sum($values); + break; + + default: + var_dump("unsupport aggr " . $a_aggr_value); + break; + } + } + } + + return $res; + } + + protected static function buildFullPeriodData(array &$a_res, $a_day_from, $a_day_to, $a_last_before_period, $a_allow_zero = false) + { + // build full data for period + $safety = 0; + $last = null; + $today = date("Y-m-d"); + $current = explode("-", $a_day_from); + $current = date("Y-m-d", mktime(0, 0, 1, $current[1], $current[2], $current[0])); + while ($current <= $a_day_to && + ++$safety < 1000) { + if (!isset($a_res[$current])) { + if ($current <= $today) { + // last existing value in period + if ($last !== null) { + $a_res[$current] = $last; + } + // last existing value before period + elseif ($a_last_before_period || $a_allow_zero) { + $a_res[$current] = $a_last_before_period; + } + } + } else { + $last = $a_res[$current]; + } + + $current = explode("-", $current); + $current = date("Y-m-d", mktime(0, 0, 1, $current[1], $current[2]+1, $current[0])); + } + } + + + // + // READ WIKI + // + + protected static function getWikiNumPages($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat", "num_pages", "MAX(%s)", null, null, true); + } + + protected static function getWikiNewPagesSum($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_user", "new_pages", "SUM(%s)"); + } + + protected static function getWikiNewPagesAvg($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_user", "new_pages", "user_id", "AVG(%s)", "SUM(%s)"); + } + + protected static function getWikiDeletedPages($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat", "del_pages", "SUM(%s)"); + } + + protected static function getWikiReadPages($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page_user", "read_events", "SUM(%s)"); + } + + protected static function getWikiEditPagesSum($a_wiki_id, $a_day_from, $a_day_to) + { + global $DIC; - $ilDB = $DIC->database(); - - $res = array(); - - if(!$a_build_full_period) - { - $sql = "SELECT ts_day, ".sprintf($a_aggr_value, $a_field)." ".$a_field. - " FROM (". - // subquery to build average per $a_aggr_by - " SELECT ts_day, ".sprintf($a_aggr_sub, $a_field)." ".$a_field. - " FROM ".$a_table. - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND ts_day >= ".$ilDB->quote($a_day_from, "text"). - " AND ts_day <= ".$ilDB->quote($a_day_to, "text"). - " AND ".$a_field." > ".$ilDB->quote(0, "integer"). - " AND ".$a_field." IS NOT NULL"; - if($a_sub_field) - { - $sql .= " AND ".$a_sub_field." = ".$ilDB->quote($a_sub_id, "integer"); - } - $sql .= " GROUP BY ts_day, ".$a_aggr_by. - ") aggr_sub". - " GROUP BY ts_day". - " ORDER BY ts_day"; - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $res[$row["ts_day"]] = $row[$a_field]; - } - } - else - { - $tmp = $all_aggr_ids = $deleted_in_period = $first_day_in_period = array(); - - if($a_table != "wiki_stat_page") - { - echo "can only build full period averages for wiki_stat_page"; - exit(); - } - - // as current period can be totally empty, gather existing subs - $sql = " SELECT *". - " FROM (". - " SELECT ".$a_aggr_by.", MAX(deleted) deleted, MAX(ts_day) last_day, MIN(ts_day) first_day". - " FROM ".$a_table. - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " GROUP BY ".$a_aggr_by. - ") aggr_sub". - " WHERE first_day <= ".$ilDB->quote($a_day_to, "text"). // not created after period - " AND (last_day >= ".$ilDB->quote($a_day_from, "text"). // (deleted in/after period - " OR deleted = ".$ilDB->quote(0, "integer").")"; // or still existing) - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $all_aggr_ids[] = $row[$a_aggr_by]; - - // if deleted in period we need the last day - if($row["deleted"] && $row["last_day"] < $a_day_to) - { - $deleted_in_period[$row[$a_aggr_by]] = $row["last_day"]; - } - // if created in period we need the first day - if($row["first_day"] > $a_day_from) - { - $first_day_in_period[$row[$a_aggr_by]] = $row["first_day"]; - } - } - - // we need to build average manually after completing period data (zero is valid) - $sql = " SELECT ts_day, ".$a_aggr_by.", ".sprintf($a_aggr_sub, $a_field)." ".$a_field. - " FROM ".$a_table. - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND ts_day >= ".$ilDB->quote($a_day_from, "text"). - " AND ts_day <= ".$ilDB->quote($a_day_to, "text"); - $sql .= " GROUP BY ts_day, ".$a_aggr_by; - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - if(!in_array($row[$a_aggr_by], $all_aggr_ids)) - { - var_dump("unexpected wiki_stat_page_entry", $row); - } - $tmp[$row[$a_aggr_by]][$row["ts_day"]] = $row[$a_field]; - } - - // build full period for each sub - foreach($all_aggr_ids as $aggr_by_id) - { - // last of entry of sub is before period - if(!is_array($tmp[$aggr_by_id])) - { - $tmp[$aggr_by_id] = array(); - } - - // get last value before period to add missing entries in period - $last_before_period = null; - if(!$tmp[$aggr_by_id][$a_day_from]) - { - $last_before_period = self::getWikiLast($a_wiki_id, $a_day_from, $a_table, $a_field, $a_aggr_by, $aggr_by_id); - } - - // if sub was created in period (see above), shorten period accordingly - $first_period_day = isset($first_day_in_period[$aggr_by_id]) - ? $first_day_in_period[$aggr_by_id] - : $a_day_from; - - // if sub was deleted in period (see above), shorten period accordingly - $last_period_day = isset($deleted_in_period[$aggr_by_id]) - ? $deleted_in_period[$aggr_by_id] - : $a_day_to; - - // allow zero as we need to correct number of valid subs per day (see below - AVG) - self::buildFullPeriodData($tmp[$aggr_by_id], $first_period_day, $last_period_day, $last_before_period, true); - - // distribute sub to days - foreach($tmp[$aggr_by_id] as $day => $value) - { - $res[$day][$aggr_by_id] = $value; - } - } - - // build average over subs - foreach($res as $day => $values) - { - switch($a_aggr_value) - { - case "AVG(%s)": - $res[$day] = array_sum($values)/sizeof($values); - break; - - case "SUM(%s)": - $res[$day] = array_sum($values); - break; - - default: - var_dump("unsupport aggr ".$a_aggr_value); - break; - } - } - } - - return $res; - } - - protected static function buildFullPeriodData(array &$a_res, $a_day_from, $a_day_to, $a_last_before_period, $a_allow_zero = false) - { - // build full data for period - $safety = 0; - $last = null; - $today = date("Y-m-d"); - $current = explode("-", $a_day_from); - $current = date("Y-m-d", mktime(0, 0, 1, $current[1], $current[2], $current[0])); - while($current <= $a_day_to && - ++$safety < 1000) - { - if(!isset($a_res[$current])) - { - if($current <= $today) - { - // last existing value in period - if($last !== null) - { - $a_res[$current] = $last; - } - // last existing value before period - else if($a_last_before_period || $a_allow_zero) - { - $a_res[$current] = $a_last_before_period; - } - } - } - else - { - $last = $a_res[$current]; - } - - $current = explode("-", $current); - $current = date("Y-m-d", mktime(0, 0, 1, $current[1], $current[2]+1, $current[0])); - } - } - - - // - // READ WIKI - // - - protected static function getWikiNumPages($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat", "num_pages", "MAX(%s)", null, null, true); - } - - protected static function getWikiNewPagesSum($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_user", "new_pages", "SUM(%s)"); - } - - protected static function getWikiNewPagesAvg($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_user", "new_pages", "user_id", "AVG(%s)", "SUM(%s)"); - } - - protected static function getWikiDeletedPages($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat", "del_pages", "SUM(%s)"); - } - - protected static function getWikiReadPages($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page_user", "read_events", "SUM(%s)"); - } - - protected static function getWikiEditPagesSum($a_wiki_id, $a_day_from, $a_day_to) - { - global $DIC; + $ilDB = $DIC->database(); + + $res = array(); + + $sql = "SELECT ts_day, COUNT(DISTINCT(page_id)) num_changed_pages" . + " FROM wiki_stat_page_user" . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND ts_day >= " . $ilDB->quote($a_day_from, "text") . + " AND ts_day <= " . $ilDB->quote($a_day_to, "text") . + " AND changes > " . $ilDB->quote(0, "integer") . + " AND changes IS NOT NULL" . + " GROUP BY ts_day" . + " ORDER BY ts_day"; + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $res[$row["ts_day"]] = $row["num_changed_pages"]; + } + + return $res; + } + + protected static function getWikiEditPagesAvg($a_wiki_id, $a_day_from, $a_day_to) + { + global $DIC; - $ilDB = $DIC->database(); - - $res = array(); - - $sql = "SELECT ts_day, COUNT(DISTINCT(page_id)) num_changed_pages". - " FROM wiki_stat_page_user". - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND ts_day >= ".$ilDB->quote($a_day_from, "text"). - " AND ts_day <= ".$ilDB->quote($a_day_to, "text"). - " AND changes > ".$ilDB->quote(0, "integer"). - " AND changes IS NOT NULL". - " GROUP BY ts_day". - " ORDER BY ts_day"; - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $res[$row["ts_day"]] = $row["num_changed_pages"]; - } - - return $res; - } - - protected static function getWikiEditPagesAvg($a_wiki_id, $a_day_from, $a_day_to) - { - global $DIC; + $ilDB = $DIC->database(); + + $res = array(); + + $sql = "SELECT ts_day, AVG(num_changed_pages) num_changed_pages" . + " FROM (" . + // subquery to build average per user + " SELECT ts_day, COUNT(DISTINCT(page_id)) num_changed_pages" . + " FROM wiki_stat_page_user" . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND ts_day >= " . $ilDB->quote($a_day_from, "text") . + " AND ts_day <= " . $ilDB->quote($a_day_to, "text") . + " AND changes > " . $ilDB->quote(0, "integer") . + " AND changes IS NOT NULL" . + " GROUP BY ts_day, user_id" . + ") aggr_user" . + " GROUP BY ts_day" . + " ORDER BY ts_day"; + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $res[$row["ts_day"]] = $row["num_changed_pages"]; + } + + return $res; + } + + protected static function getWikiUserEditPages($a_wiki_id, $a_day_from, $a_day_to, $a_sub_field = null, $a_sub_id = null) + { + global $DIC; - $ilDB = $DIC->database(); - - $res = array(); - - $sql = "SELECT ts_day, AVG(num_changed_pages) num_changed_pages". - " FROM (". - // subquery to build average per user - " SELECT ts_day, COUNT(DISTINCT(page_id)) num_changed_pages". - " FROM wiki_stat_page_user". - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND ts_day >= ".$ilDB->quote($a_day_from, "text"). - " AND ts_day <= ".$ilDB->quote($a_day_to, "text"). - " AND changes > ".$ilDB->quote(0, "integer"). - " AND changes IS NOT NULL". - " GROUP BY ts_day, user_id". - ") aggr_user". - " GROUP BY ts_day". - " ORDER BY ts_day"; - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $res[$row["ts_day"]] = $row["num_changed_pages"]; - } - - return $res; - } - - protected static function getWikiUserEditPages($a_wiki_id, $a_day_from, $a_day_to, $a_sub_field = null, $a_sub_id = null) - { - global $DIC; + $ilDB = $DIC->database(); + + $res = array(); + + $sql = "SELECT ts_day, COUNT(DISTINCT(user_id)) num_changed_users" . + " FROM wiki_stat_page_user" . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND ts_day >= " . $ilDB->quote($a_day_from, "text") . + " AND ts_day <= " . $ilDB->quote($a_day_to, "text") . + " AND changes > " . $ilDB->quote(0, "integer") . + " AND changes IS NOT NULL"; + if ($a_sub_field) { + $sql .= " AND " . $a_sub_field . " = " . $ilDB->quote($a_sub_id, "integer"); + } + $sql .= " GROUP BY ts_day" . + " ORDER BY ts_day"; + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $res[$row["ts_day"]] = $row["num_changed_users"]; + } + + return $res; + } + + protected static function getWikiUserEditPagesAvg($a_wiki_id, $a_day_from, $a_day_to) + { + global $DIC; - $ilDB = $DIC->database(); - - $res = array(); - - $sql = "SELECT ts_day, COUNT(DISTINCT(user_id)) num_changed_users". - " FROM wiki_stat_page_user". - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND ts_day >= ".$ilDB->quote($a_day_from, "text"). - " AND ts_day <= ".$ilDB->quote($a_day_to, "text"). - " AND changes > ".$ilDB->quote(0, "integer"). - " AND changes IS NOT NULL"; - if($a_sub_field) - { - $sql .= " AND ".$a_sub_field." = ".$ilDB->quote($a_sub_id, "integer"); - } - $sql .= " GROUP BY ts_day". - " ORDER BY ts_day"; - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $res[$row["ts_day"]] = $row["num_changed_users"]; - } - - return $res; - } - - protected static function getWikiUserEditPagesAvg($a_wiki_id, $a_day_from, $a_day_to) - { - global $DIC; + $ilDB = $DIC->database(); + + $res = array(); + + $sql = "SELECT ts_day, AVG(num_changed_users) num_changed_users" . + " FROM (" . + // subquery to build average per page + " SELECT ts_day, COUNT(DISTINCT(user_id)) num_changed_users" . + " FROM wiki_stat_page_user" . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND ts_day >= " . $ilDB->quote($a_day_from, "text") . + " AND ts_day <= " . $ilDB->quote($a_day_to, "text") . + " AND changes > " . $ilDB->quote(0, "integer") . + " AND changes IS NOT NULL" . + " GROUP BY ts_day, page_id" . + ") aggr_user" . + " GROUP BY ts_day" . + " ORDER BY ts_day"; + $set = $ilDB->query($sql); + while ($row = $ilDB->fetchAssoc($set)) { + $res[$row["ts_day"]] = $row["num_changed_users"]; + } + + return $res; + } + + protected static function getWikiNumRating($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_ratings", "SUM(%s)"); + } + + protected static function getWikiNumRatingAvg($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_ratings", "page_id", "AVG(%s)", "SUM(%s)"); + } + + protected static function getWikiRatingAvg($a_wiki_id, $a_day_from, $a_day_to) + { + $res = self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat", "avg_rating", "AVG(%s)"); + + foreach (array_keys($res) as $day) { + // int-to-float + $res[$day] = $res[$day]/100; + } + + return $res; + } + + protected static function getWikiInternalLinks($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "int_links", "page_id", "SUM(%s)", "MAX(%s)", null, null, true); + } + + protected static function getWikiInternalLinksAvg($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "int_links", "page_id", "AVG(%s)", "MAX(%s)", null, null, true); + } + + protected static function getWikiExternalLinks($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "ext_links", "page_id", "SUM(%s)", "MAX(%s)", null, null, true); + } + + protected static function getWikiExternalLinksAvg($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "ext_links", "page_id", "AVG(%s)", "MAX(%s)", null, null, true); + } + + protected static function getWikiWords($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_words", "page_id", "SUM(%s)", "MAX(%s)", null, null, true); + } + + protected static function getWikiWordsAvg($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_words", "page_id", "AVG(%s)", "MAX(%s)", null, null, true); + } + + protected static function getWikiCharacters($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_chars", "page_id", "SUM(%s)", "MAX(%s)", null, null, true); + } + + protected static function getWikiCharactersAvg($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_chars", "page_id", "AVG(%s)", "MAX(%s)", null, null, true); + } + + protected static function getWikiFootnotes($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "footnotes", "page_id", "SUM(%s)", "MAX(%s)", null, null, true); + } + + protected static function getWikiFootnotesAvg($a_wiki_id, $a_day_from, $a_day_to) + { + return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "footnotes", "page_id", "AVG(%s)", "MAX(%s)", null, null, true); + } + + + // + // READ PAGE + // + + protected static function getWikiPageChanges($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) + { + return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page_user", "changes", "SUM(%s)", "page_id", $a_page_id); + } + + protected static function getWikiPageChangesAvg($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) + { + return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page_user", "changes", "user_id", "AVG(%s)", "SUM(%s)", "page_id", $a_page_id); + } + + protected static function getWikiPageUserEdit($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) + { + return self::getWikiUserEditPages($a_wiki_id, $a_day_from, $a_day_to, "page_id", $a_page_id); + } + + protected static function getWikiPageRead($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) + { + return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page_user", "read_events", "SUM(%s)", "page_id", $a_page_id); + } + + protected static function getWikiPageInternalLinks($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) + { + return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "int_links", "MAX(%s)", "page_id", $a_page_id, true); + } + + protected static function getWikiPageExternalLinks($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) + { + return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "ext_links", "MAX(%s)", "page_id", $a_page_id, true); + } + + protected static function getWikiPageWords($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) + { + return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_words", "MAX(%s)", "page_id", $a_page_id, true); + } + + protected static function getWikiPageCharacters($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) + { + return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_chars", "MAX(%s)", "page_id", $a_page_id, true); + } + + protected static function getWikiPageFootnotes($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) + { + return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "footnotes", "MAX(%s)", "page_id", $a_page_id, true); + } + + protected static function getWikiPageRatings($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) + { + return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_ratings", "SUM(%s)", "page_id", $a_page_id); + } + + + // + // GUI HELPER + // - $ilDB = $DIC->database(); - - $res = array(); - - $sql = "SELECT ts_day, AVG(num_changed_users) num_changed_users". - " FROM (". - // subquery to build average per page - " SELECT ts_day, COUNT(DISTINCT(user_id)) num_changed_users". - " FROM wiki_stat_page_user". - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND ts_day >= ".$ilDB->quote($a_day_from, "text"). - " AND ts_day <= ".$ilDB->quote($a_day_to, "text"). - " AND changes > ".$ilDB->quote(0, "integer"). - " AND changes IS NOT NULL". - " GROUP BY ts_day, page_id". - ") aggr_user". - " GROUP BY ts_day". - " ORDER BY ts_day"; - $set = $ilDB->query($sql); - while($row = $ilDB->fetchAssoc($set)) - { - $res[$row["ts_day"]] = $row["num_changed_users"]; - } - - return $res; - } - - protected static function getWikiNumRating($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_ratings", "SUM(%s)"); - } - - protected static function getWikiNumRatingAvg($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_ratings", "page_id", "AVG(%s)", "SUM(%s)"); - } - - protected static function getWikiRatingAvg($a_wiki_id, $a_day_from, $a_day_to) - { - $res = self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat", "avg_rating", "AVG(%s)"); - - foreach(array_keys($res) as $day) - { - // int-to-float - $res[$day] = $res[$day]/100; - } - - return $res; - } - - protected static function getWikiInternalLinks($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "int_links", "page_id", "SUM(%s)", "MAX(%s)", null, null, true); - } - - protected static function getWikiInternalLinksAvg($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "int_links", "page_id", "AVG(%s)", "MAX(%s)", null, null, true); - } - - protected static function getWikiExternalLinks($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "ext_links", "page_id", "SUM(%s)", "MAX(%s)", null, null, true); - } - - protected static function getWikiExternalLinksAvg($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "ext_links", "page_id", "AVG(%s)", "MAX(%s)", null, null, true); - } - - protected static function getWikiWords($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_words", "page_id", "SUM(%s)", "MAX(%s)", null, null, true); - } - - protected static function getWikiWordsAvg($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_words", "page_id", "AVG(%s)", "MAX(%s)", null, null, true); - } - - protected static function getWikiCharacters($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_chars", "page_id", "SUM(%s)", "MAX(%s)", null, null, true); - } - - protected static function getWikiCharactersAvg($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_chars", "page_id", "AVG(%s)", "MAX(%s)", null, null, true); - } - - protected static function getWikiFootnotes($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "footnotes", "page_id", "SUM(%s)", "MAX(%s)", null, null, true); - } - - protected static function getWikiFootnotesAvg($a_wiki_id, $a_day_from, $a_day_to) - { - return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "footnotes", "page_id", "AVG(%s)", "MAX(%s)", null, null, true); - } - - - // - // READ PAGE - // - - protected static function getWikiPageChanges($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) - { - return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page_user", "changes", "SUM(%s)", "page_id", $a_page_id); - } - - protected static function getWikiPageChangesAvg($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) - { - return self::getWikiAggrSub($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page_user", "changes", "user_id", "AVG(%s)", "SUM(%s)", "page_id", $a_page_id); - } - - protected static function getWikiPageUserEdit($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) - { - return self::getWikiUserEditPages($a_wiki_id, $a_day_from, $a_day_to, "page_id", $a_page_id); - } - - protected static function getWikiPageRead($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) - { - return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page_user", "read_events", "SUM(%s)", "page_id", $a_page_id); - } - - protected static function getWikiPageInternalLinks($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) - { - return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "int_links", "MAX(%s)", "page_id", $a_page_id, true); - } - - protected static function getWikiPageExternalLinks($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) - { - return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "ext_links", "MAX(%s)", "page_id", $a_page_id, true); - } - - protected static function getWikiPageWords($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) - { - return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_words", "MAX(%s)", "page_id", $a_page_id, true); - } - - protected static function getWikiPageCharacters($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) - { - return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_chars", "MAX(%s)", "page_id", $a_page_id, true); - } - - protected static function getWikiPageFootnotes($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) - { - return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "footnotes", "MAX(%s)", "page_id", $a_page_id, true); - } - - protected static function getWikiPageRatings($a_wiki_id, $a_page_id, $a_day_from, $a_day_to) - { - return self::getWikiAggr($a_wiki_id, $a_day_from, $a_day_to, "wiki_stat_page", "num_ratings", "SUM(%s)", "page_id", $a_page_id); - } - - - // - // GUI HELPER - // + public static function getAvailableMonths($a_wiki_id) + { + global $DIC; - public static function getAvailableMonths($a_wiki_id) - { - global $DIC; + $ilDB = $DIC->database(); + + $res = array(); + + // because of read_events this db table is updated most often + $set = $ilDB->query("SELECT DISTINCT(SUBSTR(ts_day, 1, 7)) " . $ilDB->quoteIdentifier("month") . + " FROM wiki_stat_page_user" . + " WHERE wiki_id = " . $ilDB->quote($a_wiki_id, "integer") . + " AND ts_day IS NOT NULL"); + while ($row = $ilDB->fetchAssoc($set)) { + $res[] = $row["month"]; + } + + return $res; + } + + public static function getFigures() + { + return array( + self::KEY_FIGURE_WIKI_NUM_PAGES + ,self::KEY_FIGURE_WIKI_NEW_PAGES + ,self::KEY_FIGURE_WIKI_NEW_PAGES_AVG + ,self::KEY_FIGURE_WIKI_EDIT_PAGES + ,self::KEY_FIGURE_WIKI_EDIT_PAGES_AVG + ,self::KEY_FIGURE_WIKI_DELETED_PAGES + ,self::KEY_FIGURE_WIKI_READ_PAGES + ,self::KEY_FIGURE_WIKI_USER_EDIT_PAGES + ,self::KEY_FIGURE_WIKI_USER_EDIT_PAGES_AVG + ,self::KEY_FIGURE_WIKI_NUM_RATING + ,self::KEY_FIGURE_WIKI_NUM_RATING_AVG + ,self::KEY_FIGURE_WIKI_RATING_AVG + ,self::KEY_FIGURE_WIKI_INTERNAL_LINKS + ,self::KEY_FIGURE_WIKI_INTERNAL_LINKS_AVG + ,self::KEY_FIGURE_WIKI_EXTERNAL_LINKS + ,self::KEY_FIGURE_WIKI_EXTERNAL_LINKS_AVG + ,self::KEY_FIGURE_WIKI_WORDS + ,self::KEY_FIGURE_WIKI_WORDS_AVG + ,self::KEY_FIGURE_WIKI_CHARS + ,self::KEY_FIGURE_WIKI_CHARS_AVG + ,self::KEY_FIGURE_WIKI_FOOTNOTES + ,self::KEY_FIGURE_WIKI_FOOTNOTES_AVG + ); + } + + public static function getFiguresPage() + { + return array( + self::KEY_FIGURE_WIKI_PAGE_CHANGES + ,self::KEY_FIGURE_WIKI_PAGE_CHANGES_AVG + ,self::KEY_FIGURE_WIKI_PAGE_USER_EDIT + ,self::KEY_FIGURE_WIKI_PAGE_READ + ,self::KEY_FIGURE_WIKI_PAGE_INTERNAL_LINKS + ,self::KEY_FIGURE_WIKI_PAGE_EXTERNAL_LINKS + ,self::KEY_FIGURE_WIKI_PAGE_WORDS + ,self::KEY_FIGURE_WIKI_PAGE_CHARS + ,self::KEY_FIGURE_WIKI_PAGE_FOOTNOTES + ,self::KEY_FIGURE_WIKI_PAGE_RATINGS + ); + } + + public static function getFigureTitle($a_figure) + { + global $DIC; - $ilDB = $DIC->database(); - - $res = array(); - - // because of read_events this db table is updated most often - $set = $ilDB->query("SELECT DISTINCT(SUBSTR(ts_day, 1, 7)) ".$ilDB->quoteIdentifier("month"). - " FROM wiki_stat_page_user". - " WHERE wiki_id = ".$ilDB->quote($a_wiki_id, "integer"). - " AND ts_day IS NOT NULL"); - while($row = $ilDB->fetchAssoc($set)) - { - $res[] = $row["month"]; - } - - return $res; - } - - public static function getFigures() - { - return array( - self::KEY_FIGURE_WIKI_NUM_PAGES - ,self::KEY_FIGURE_WIKI_NEW_PAGES - ,self::KEY_FIGURE_WIKI_NEW_PAGES_AVG - ,self::KEY_FIGURE_WIKI_EDIT_PAGES - ,self::KEY_FIGURE_WIKI_EDIT_PAGES_AVG - ,self::KEY_FIGURE_WIKI_DELETED_PAGES - ,self::KEY_FIGURE_WIKI_READ_PAGES - ,self::KEY_FIGURE_WIKI_USER_EDIT_PAGES - ,self::KEY_FIGURE_WIKI_USER_EDIT_PAGES_AVG - ,self::KEY_FIGURE_WIKI_NUM_RATING - ,self::KEY_FIGURE_WIKI_NUM_RATING_AVG - ,self::KEY_FIGURE_WIKI_RATING_AVG - ,self::KEY_FIGURE_WIKI_INTERNAL_LINKS - ,self::KEY_FIGURE_WIKI_INTERNAL_LINKS_AVG - ,self::KEY_FIGURE_WIKI_EXTERNAL_LINKS - ,self::KEY_FIGURE_WIKI_EXTERNAL_LINKS_AVG - ,self::KEY_FIGURE_WIKI_WORDS - ,self::KEY_FIGURE_WIKI_WORDS_AVG - ,self::KEY_FIGURE_WIKI_CHARS - ,self::KEY_FIGURE_WIKI_CHARS_AVG - ,self::KEY_FIGURE_WIKI_FOOTNOTES - ,self::KEY_FIGURE_WIKI_FOOTNOTES_AVG - ); - } - - public static function getFiguresPage() - { - return array( - self::KEY_FIGURE_WIKI_PAGE_CHANGES - ,self::KEY_FIGURE_WIKI_PAGE_CHANGES_AVG - ,self::KEY_FIGURE_WIKI_PAGE_USER_EDIT - ,self::KEY_FIGURE_WIKI_PAGE_READ - ,self::KEY_FIGURE_WIKI_PAGE_INTERNAL_LINKS - ,self::KEY_FIGURE_WIKI_PAGE_EXTERNAL_LINKS - ,self::KEY_FIGURE_WIKI_PAGE_WORDS - ,self::KEY_FIGURE_WIKI_PAGE_CHARS - ,self::KEY_FIGURE_WIKI_PAGE_FOOTNOTES - ,self::KEY_FIGURE_WIKI_PAGE_RATINGS - ); - } - - public static function getFigureTitle($a_figure) - { - global $DIC; + $lng = $DIC->language(); + + $map = array( + // wiki + self::KEY_FIGURE_WIKI_NUM_PAGES => $lng->txt("wiki_stat_num_pages") + ,self::KEY_FIGURE_WIKI_NEW_PAGES => $lng->txt("wiki_stat_new_pages") + ,self::KEY_FIGURE_WIKI_NEW_PAGES_AVG => $lng->txt("wiki_stat_new_pages_avg") + ,self::KEY_FIGURE_WIKI_EDIT_PAGES => $lng->txt("wiki_stat_edit_pages") + ,self::KEY_FIGURE_WIKI_EDIT_PAGES_AVG => $lng->txt("wiki_stat_edit_pages_avg") + ,self::KEY_FIGURE_WIKI_DELETED_PAGES => $lng->txt("wiki_stat_deleted_pages") + ,self::KEY_FIGURE_WIKI_READ_PAGES => $lng->txt("wiki_stat_read_pages") + ,self::KEY_FIGURE_WIKI_USER_EDIT_PAGES => $lng->txt("wiki_stat_user_edit_pages") + ,self::KEY_FIGURE_WIKI_USER_EDIT_PAGES_AVG => $lng->txt("wiki_stat_user_edit_pages_avg") + ,self::KEY_FIGURE_WIKI_NUM_RATING => $lng->txt("wiki_stat_num_rating") + ,self::KEY_FIGURE_WIKI_NUM_RATING_AVG => $lng->txt("wiki_stat_num_rating_avg") + ,self::KEY_FIGURE_WIKI_RATING_AVG => $lng->txt("wiki_stat_rating_avg") + ,self::KEY_FIGURE_WIKI_INTERNAL_LINKS => $lng->txt("wiki_stat_internal_links") + ,self::KEY_FIGURE_WIKI_INTERNAL_LINKS_AVG => $lng->txt("wiki_stat_internal_links_avg") + ,self::KEY_FIGURE_WIKI_EXTERNAL_LINKS => $lng->txt("wiki_stat_external_links") + ,self::KEY_FIGURE_WIKI_EXTERNAL_LINKS_AVG => $lng->txt("wiki_stat_external_links_avg") + ,self::KEY_FIGURE_WIKI_WORDS => $lng->txt("wiki_stat_words") + ,self::KEY_FIGURE_WIKI_WORDS_AVG => $lng->txt("wiki_stat_words_avg") + ,self::KEY_FIGURE_WIKI_CHARS => $lng->txt("wiki_stat_chars") + ,self::KEY_FIGURE_WIKI_CHARS_AVG => $lng->txt("wiki_stat_chars_avg") + ,self::KEY_FIGURE_WIKI_FOOTNOTES => $lng->txt("wiki_stat_footnotes") + ,self::KEY_FIGURE_WIKI_FOOTNOTES_AVG => $lng->txt("wiki_stat_footnotes_avg") + // page + ,self::KEY_FIGURE_WIKI_PAGE_CHANGES => $lng->txt("wiki_stat_page_changes") + ,self::KEY_FIGURE_WIKI_PAGE_CHANGES_AVG => $lng->txt("wiki_stat_page_changes_avg") + ,self::KEY_FIGURE_WIKI_PAGE_USER_EDIT => $lng->txt("wiki_stat_page_user_edit") + ,self::KEY_FIGURE_WIKI_PAGE_READ => $lng->txt("wiki_stat_page_read") + ,self::KEY_FIGURE_WIKI_PAGE_INTERNAL_LINKS => $lng->txt("wiki_stat_page_internal_links") + ,self::KEY_FIGURE_WIKI_PAGE_EXTERNAL_LINKS => $lng->txt("wiki_stat_page_external_links") + ,self::KEY_FIGURE_WIKI_PAGE_WORDS => $lng->txt("wiki_stat_page_words") + ,self::KEY_FIGURE_WIKI_PAGE_CHARS => $lng->txt("wiki_stat_page_characters") + ,self::KEY_FIGURE_WIKI_PAGE_FOOTNOTES => $lng->txt("wiki_stat_page_footnotes") + ,self::KEY_FIGURE_WIKI_PAGE_RATINGS => $lng->txt("wiki_stat_page_ratings") + ); + + return $map[$a_figure]; + } + + public static function getFigureData($a_wiki_id, $a_figure, $a_from, $a_to) + { + switch ($a_figure) { + case self::KEY_FIGURE_WIKI_NUM_PAGES: + return self::getWikiNumPages($a_wiki_id, $a_from, $a_to); - $lng = $DIC->language(); - - $map = array( - // wiki - self::KEY_FIGURE_WIKI_NUM_PAGES => $lng->txt("wiki_stat_num_pages") - ,self::KEY_FIGURE_WIKI_NEW_PAGES => $lng->txt("wiki_stat_new_pages") - ,self::KEY_FIGURE_WIKI_NEW_PAGES_AVG => $lng->txt("wiki_stat_new_pages_avg") - ,self::KEY_FIGURE_WIKI_EDIT_PAGES => $lng->txt("wiki_stat_edit_pages") - ,self::KEY_FIGURE_WIKI_EDIT_PAGES_AVG => $lng->txt("wiki_stat_edit_pages_avg") - ,self::KEY_FIGURE_WIKI_DELETED_PAGES => $lng->txt("wiki_stat_deleted_pages") - ,self::KEY_FIGURE_WIKI_READ_PAGES => $lng->txt("wiki_stat_read_pages") - ,self::KEY_FIGURE_WIKI_USER_EDIT_PAGES => $lng->txt("wiki_stat_user_edit_pages") - ,self::KEY_FIGURE_WIKI_USER_EDIT_PAGES_AVG => $lng->txt("wiki_stat_user_edit_pages_avg") - ,self::KEY_FIGURE_WIKI_NUM_RATING => $lng->txt("wiki_stat_num_rating") - ,self::KEY_FIGURE_WIKI_NUM_RATING_AVG => $lng->txt("wiki_stat_num_rating_avg") - ,self::KEY_FIGURE_WIKI_RATING_AVG => $lng->txt("wiki_stat_rating_avg") - ,self::KEY_FIGURE_WIKI_INTERNAL_LINKS => $lng->txt("wiki_stat_internal_links") - ,self::KEY_FIGURE_WIKI_INTERNAL_LINKS_AVG => $lng->txt("wiki_stat_internal_links_avg") - ,self::KEY_FIGURE_WIKI_EXTERNAL_LINKS => $lng->txt("wiki_stat_external_links") - ,self::KEY_FIGURE_WIKI_EXTERNAL_LINKS_AVG => $lng->txt("wiki_stat_external_links_avg") - ,self::KEY_FIGURE_WIKI_WORDS => $lng->txt("wiki_stat_words") - ,self::KEY_FIGURE_WIKI_WORDS_AVG => $lng->txt("wiki_stat_words_avg") - ,self::KEY_FIGURE_WIKI_CHARS => $lng->txt("wiki_stat_chars") - ,self::KEY_FIGURE_WIKI_CHARS_AVG => $lng->txt("wiki_stat_chars_avg") - ,self::KEY_FIGURE_WIKI_FOOTNOTES => $lng->txt("wiki_stat_footnotes") - ,self::KEY_FIGURE_WIKI_FOOTNOTES_AVG => $lng->txt("wiki_stat_footnotes_avg") - // page - ,self::KEY_FIGURE_WIKI_PAGE_CHANGES => $lng->txt("wiki_stat_page_changes") - ,self::KEY_FIGURE_WIKI_PAGE_CHANGES_AVG => $lng->txt("wiki_stat_page_changes_avg") - ,self::KEY_FIGURE_WIKI_PAGE_USER_EDIT => $lng->txt("wiki_stat_page_user_edit") - ,self::KEY_FIGURE_WIKI_PAGE_READ => $lng->txt("wiki_stat_page_read") - ,self::KEY_FIGURE_WIKI_PAGE_INTERNAL_LINKS => $lng->txt("wiki_stat_page_internal_links") - ,self::KEY_FIGURE_WIKI_PAGE_EXTERNAL_LINKS => $lng->txt("wiki_stat_page_external_links") - ,self::KEY_FIGURE_WIKI_PAGE_WORDS => $lng->txt("wiki_stat_page_words") - ,self::KEY_FIGURE_WIKI_PAGE_CHARS => $lng->txt("wiki_stat_page_characters") - ,self::KEY_FIGURE_WIKI_PAGE_FOOTNOTES => $lng->txt("wiki_stat_page_footnotes") - ,self::KEY_FIGURE_WIKI_PAGE_RATINGS => $lng->txt("wiki_stat_page_ratings") - ); - - return $map[$a_figure]; - } - - public static function getFigureData($a_wiki_id, $a_figure, $a_from, $a_to) - { - switch($a_figure) - { - case self::KEY_FIGURE_WIKI_NUM_PAGES: - return self::getWikiNumPages($a_wiki_id, $a_from, $a_to); + case self::KEY_FIGURE_WIKI_NEW_PAGES: + return self::getWikiNewPagesSum($a_wiki_id, $a_from, $a_to); - case self::KEY_FIGURE_WIKI_NEW_PAGES: - return self::getWikiNewPagesSum($a_wiki_id, $a_from, $a_to); + case self::KEY_FIGURE_WIKI_NEW_PAGES_AVG: + return self::getWikiNewPagesAvg($a_wiki_id, $a_from, $a_to); - case self::KEY_FIGURE_WIKI_NEW_PAGES_AVG: - return self::getWikiNewPagesAvg($a_wiki_id, $a_from, $a_to); + case self::KEY_FIGURE_WIKI_EDIT_PAGES: + return self::getWikiEditPagesSum($a_wiki_id, $a_from, $a_to); - case self::KEY_FIGURE_WIKI_EDIT_PAGES: - return self::getWikiEditPagesSum($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_EDIT_PAGES_AVG: - return self::getWikiEditPagesAvg($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_DELETED_PAGES: - return self::getWikiDeletedPages($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_READ_PAGES: - return self::getWikiReadPages($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_USER_EDIT_PAGES: - return self::getWikiUserEditPages($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_USER_EDIT_PAGES_AVG: - return self::getWikiUserEditPages($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_NUM_RATING: - return self::getWikiNumRating($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_NUM_RATING_AVG: - return self::getWikiNumRatingAvg($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_RATING_AVG: - return self::getWikiRatingAvg($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_INTERNAL_LINKS: - return self::getWikiInternalLinks($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_INTERNAL_LINKS_AVG: - return self::getWikiInternalLinksAvg($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_EXTERNAL_LINKS: - return self::getWikiExternalLinks($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_EXTERNAL_LINKS_AVG: - return self::getWikiExternalLinksAvg($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_WORDS: - return self::getWikiWords($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_WORDS_AVG: - return self::getWikiWordsAvg($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_CHARS: - return self::getWikiCharacters($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_CHARS_AVG: - return self::getWikiCharactersAvg($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_FOOTNOTES: - return self::getWikiFootnotes($a_wiki_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_FOOTNOTES_AVG: - return self::getWikiFootnotesAvg($a_wiki_id, $a_from, $a_to); - } - } - - public static function getFigureDataPage($a_wiki_id, $a_page_id, $a_figure, $a_from, $a_to) - { - switch($a_figure) - { - case self::KEY_FIGURE_WIKI_PAGE_CHANGES: - return self::getWikiPageChanges($a_wiki_id, $a_page_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_PAGE_CHANGES_AVG: - return self::getWikiPageChangesAvg($a_wiki_id, $a_page_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_PAGE_USER_EDIT: - return self::getWikiPageUserEdit($a_wiki_id, $a_page_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_PAGE_READ: - return self::getWikiPageRead($a_wiki_id, $a_page_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_PAGE_INTERNAL_LINKS: - return self::getWikiPageInternalLinks($a_wiki_id, $a_page_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_PAGE_EXTERNAL_LINKS: - return self::getWikiPageExternalLinks($a_wiki_id, $a_page_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_PAGE_FOOTNOTES: - return self::getWikiPageFootnotes($a_wiki_id, $a_page_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_PAGE_WORDS: - return self::getWikiPageWords($a_wiki_id, $a_page_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_PAGE_CHARS: - return self::getWikiPageCharacters($a_wiki_id, $a_page_id, $a_from, $a_to); - - case self::KEY_FIGURE_WIKI_PAGE_RATINGS: - return self::getWikiPageRatings($a_wiki_id, $a_page_id, $a_from, $a_to); - } - } - - public static function getFigureOptions() - { - $res = array(); - - foreach(self::getFigures() as $figure) - { - $res[$figure] = self::getFigureTitle($figure); - } - - return $res; - } - - public static function getFigureOptionsPage() - { - $res = array(); - - foreach(self::getFiguresPage() as $figure) - { - $res[$figure] = self::getFigureTitle($figure); - } - - return $res; - } + case self::KEY_FIGURE_WIKI_EDIT_PAGES_AVG: + return self::getWikiEditPagesAvg($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_DELETED_PAGES: + return self::getWikiDeletedPages($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_READ_PAGES: + return self::getWikiReadPages($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_USER_EDIT_PAGES: + return self::getWikiUserEditPages($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_USER_EDIT_PAGES_AVG: + return self::getWikiUserEditPages($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_NUM_RATING: + return self::getWikiNumRating($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_NUM_RATING_AVG: + return self::getWikiNumRatingAvg($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_RATING_AVG: + return self::getWikiRatingAvg($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_INTERNAL_LINKS: + return self::getWikiInternalLinks($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_INTERNAL_LINKS_AVG: + return self::getWikiInternalLinksAvg($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_EXTERNAL_LINKS: + return self::getWikiExternalLinks($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_EXTERNAL_LINKS_AVG: + return self::getWikiExternalLinksAvg($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_WORDS: + return self::getWikiWords($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_WORDS_AVG: + return self::getWikiWordsAvg($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_CHARS: + return self::getWikiCharacters($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_CHARS_AVG: + return self::getWikiCharactersAvg($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_FOOTNOTES: + return self::getWikiFootnotes($a_wiki_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_FOOTNOTES_AVG: + return self::getWikiFootnotesAvg($a_wiki_id, $a_from, $a_to); + } + } + + public static function getFigureDataPage($a_wiki_id, $a_page_id, $a_figure, $a_from, $a_to) + { + switch ($a_figure) { + case self::KEY_FIGURE_WIKI_PAGE_CHANGES: + return self::getWikiPageChanges($a_wiki_id, $a_page_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_PAGE_CHANGES_AVG: + return self::getWikiPageChangesAvg($a_wiki_id, $a_page_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_PAGE_USER_EDIT: + return self::getWikiPageUserEdit($a_wiki_id, $a_page_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_PAGE_READ: + return self::getWikiPageRead($a_wiki_id, $a_page_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_PAGE_INTERNAL_LINKS: + return self::getWikiPageInternalLinks($a_wiki_id, $a_page_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_PAGE_EXTERNAL_LINKS: + return self::getWikiPageExternalLinks($a_wiki_id, $a_page_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_PAGE_FOOTNOTES: + return self::getWikiPageFootnotes($a_wiki_id, $a_page_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_PAGE_WORDS: + return self::getWikiPageWords($a_wiki_id, $a_page_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_PAGE_CHARS: + return self::getWikiPageCharacters($a_wiki_id, $a_page_id, $a_from, $a_to); + + case self::KEY_FIGURE_WIKI_PAGE_RATINGS: + return self::getWikiPageRatings($a_wiki_id, $a_page_id, $a_from, $a_to); + } + } + + public static function getFigureOptions() + { + $res = array(); + + foreach (self::getFigures() as $figure) { + $res[$figure] = self::getFigureTitle($figure); + } + + return $res; + } + + public static function getFigureOptionsPage() + { + $res = array(); + + foreach (self::getFiguresPage() as $figure) { + $res[$figure] = self::getFigureTitle($figure); + } + + return $res; + } } - -?> \ No newline at end of file diff --git a/Modules/Wiki/classes/class.ilWikiStatGUI.php b/Modules/Wiki/classes/class.ilWikiStatGUI.php index 2b8a4d83f25c953f73612037f53bc2a1e83b9d5e..3d049935b807becf34be2ff274e19600eef2ad9c 100644 --- a/Modules/Wiki/classes/class.ilWikiStatGUI.php +++ b/Modules/Wiki/classes/class.ilWikiStatGUI.php @@ -1,423 +1,387 @@ - - * @version $Id$ - * @ingroup ModulesWiki - */ -class ilWikiStatGUI -{ - /** - * @var ilCtrl - */ - protected $ctrl; + + * @version $Id$ + * @ingroup ModulesWiki + */ +class ilWikiStatGUI +{ + /** + * @var ilCtrl + */ + protected $ctrl; - protected $wiki_id; // [integer] - protected $page_id; // [integer] - - public function __construct($a_wiki_id, $a_page_id = null) - { - global $DIC; + /** + * @var ilToolbarGUI + */ + protected $toolbar; - $this->ctrl = $DIC->ctrl(); - $this->toolbar = $DIC->toolbar(); - $this->lng = $DIC->language(); - $this->tpl = $DIC["tpl"]; - $this->wiki_id = (int)$a_wiki_id; - $this->page_id = (int)$a_page_id; - } - - public function executeCommand() - { - $ilCtrl = $this->ctrl; - - $next_class = $ilCtrl->getNextClass($this); - $cmd = $ilCtrl->getCmd("view"); - - switch($next_class) - { - default: - $this->$cmd(); - break; - } - } - - protected function viewToolbar($a_is_initial = false) - { - $ilToolbar = $this->toolbar; - $lng = $this->lng; - $ilCtrl = $this->ctrl; - - $current_figure = (int)$_POST["fig"]; - $current_time_frame = (string)$_POST["tfr"]; - $current_scope = (int)$_POST["scp"]; - - include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; - $view = new ilSelectInputGUI($lng->txt("wiki_stat_figure"), "fig"); - $view->setOptions($this->page_id - ? ilWikiStat::getFigureOptionsPage() - : ilWikiStat::getFigureOptions()); - if($current_figure) - { - $view->setValue($current_figure); - } - else if($a_is_initial) - { - // default - $current_figure = $this->page_id - ? ilWikiStat::KEY_FIGURE_WIKI_PAGE_CHANGES - : ilWikiStat::KEY_FIGURE_WIKI_NUM_PAGES; - } - $ilToolbar->addInputItem($view, true); - - $options = array(); - include_once "Services/Calendar/classes/class.ilCalendarUtil.php"; - $lng->loadLanguageModule("dateplaner"); - foreach(ilWikiStat::getAvailableMonths($this->wiki_id) as $month) - { - $parts = explode("-", $month); - $options[$month] = ilCalendarUtil::_numericMonthToString((int)$parts[1]). - " ".$parts[0]; - } - krsort($options); - - $tframe = new ilSelectInputGUI($lng->txt("month"), "tfr"); - $tframe->setOptions($options); - if($current_time_frame) - { - $tframe->setValue($current_time_frame); - } - else if($a_is_initial) - { - $current_time_frame = array_shift(array_keys($options)); // default - } - $ilToolbar->addInputItem($tframe, true); - - $scope = new ilSelectInputGUI($lng->txt("wiki_stat_scope"), "scp"); - $scope->setOptions(array( - 1 => "1 ".$lng->txt("month"), - 2 => "2 ".$lng->txt("months"), - 3 => "3 ".$lng->txt("months"), - 4 => "4 ".$lng->txt("months"), - 5 => "5 ".$lng->txt("months"), - 6 => "6 ".$lng->txt("months") - )); - if($current_scope) - { - $scope->setValue($current_scope); - } - else if($a_is_initial) - { - $current_scope = 1; // default - } - $ilToolbar->addInputItem($scope, true); - - $ilToolbar->setFormAction($ilCtrl->getFormAction($this, "view")); - $ilToolbar->addFormButton($lng->txt("show"), "view"); - - if($current_figure && $current_time_frame && $current_scope) - { - $ilToolbar->addSeparator(); - $ilToolbar->addFormButton($lng->txt("export"), "export"); - - return array( - "figure" => $current_figure, - "month" => $current_time_frame, - "scope" => $current_scope - ); - } - } - - protected function export() - { - $ilCtrl = $this->ctrl; - - $params = $this->viewToolbar(); - if($params) - { - // data - - $tfr = explode("-", (string)$params["month"]); - $day_from = date("Y-m-d", mktime(0, 0, 1, $tfr[1]-($params["scope"]-1), 1, $tfr[0])); - $day_to = date("Y-m-d", mktime(0, 0, 1, $tfr[1]+1, 0, $tfr[0])); - unset($tfr); - - $chart_data = $this->getChartData($params["figure"], $params["scope"], $day_from, $day_to); - - - // excel - - $period = ilDatePresentation::formatPeriod( - new ilDate($day_from, IL_CAL_DATE), - new ilDate($day_to, IL_CAL_DATE)); - - $filename = ilObject::_lookupTitle($this->wiki_id); - if($this->page_id) - { - $filename .= " - ".ilWikiPage::lookupTitle($this->page_id); - } - $filename .= " - ".ilWikiStat::getFigureTitle($params["figure"])." - ".$period; - - include_once "./Services/Excel/classes/class.ilExcel.php"; - $excel = new ilExcel(); - $excel->addSheet($this->lng->txt("statistics")); - - $row = 1; - foreach($chart_data as $day => $value) - { - $excel->setCell($row, 0, $day); - $excel->setCell($row++, 1, $value); - } - - $excel->sendToClient($filename); - } - - $ilCtrl->redirect($this, "view"); - } - - protected function initial() - { - $this->view(true); - } - - protected function view($a_is_initial = false) - { - $tpl = $this->tpl; - $lng = $this->lng; - - $params = $this->viewToolbar($a_is_initial); - if(is_array($params)) - { - // data - - $tfr = explode("-", (string)$params["month"]); - $day_from = date("Y-m-d", mktime(0, 0, 1, $tfr[1]-($params["scope"]-1), 1, $tfr[0])); - $day_to = date("Y-m-d", mktime(0, 0, 1, $tfr[1]+1, 0, $tfr[0])); - unset($tfr); - - $chart_data = $this->getChartData($params["figure"], $params["scope"], $day_from, $day_to); - $list_data = $this->getListData(); - - - // render - - $vtpl = new ilTemplate("tpl.wiki_stat_list.html", true, true, "Modules/Wiki"); - - include_once("./Services/UIComponent/Panel/classes/class.ilPanelGUI.php"); - $chart_panel = ilPanelGUI::getInstance(); - - $vtpl->setVariable("CHART", $this->renderGraph($params["figure"], $chart_data)); - - $vtpl->setCurrentBlock("row_bl"); - $counter = 0; - foreach($list_data as $figure => $values) - { - $day = (int)substr($day, 8); - $vtpl->setVariable("CSS_ROW", ($counter++%2) ? "tblrow1" : "tblrow2"); - $vtpl->setVariable("FIGURE", $figure); - $vtpl->setVariable("YESTERDAY_VALUE", $values["yesterday"]); - $vtpl->setVariable("TODAY_VALUE", $values["today"]); - $vtpl->parseCurrentBlock(); - } - - $vtpl->setVariable("FIGURE_HEAD", $lng->txt("wiki_stat_figure")); - $vtpl->setVariable("YESTERDAY_HEAD", $lng->txt("yesterday")); - $vtpl->setVariable("TODAY_HEAD", $lng->txt("today")); - - $chart_panel->setHeading($lng->txt("statistics")); - $chart_panel->setBody($vtpl->get()); - $chart_panel->setHeadingStyle(ilPanelGUI::HEADING_STYLE_SUBHEADING); - - $tpl->setContent($chart_panel->getHTML()); - } - } - - protected function getChartData($a_figure, $a_scope, $a_from, $a_to) - { - $data = array(); - - $raw = $this->page_id - ? ilWikiStat::getFigureDataPage($this->wiki_id, $this->page_id, $a_figure, $a_from, $a_to) - : ilWikiStat::getFigureData($this->wiki_id, $a_figure, $a_from, $a_to); - - $parts = explode("-", $a_from); - for($loop = 0; $loop <= ($a_scope*31); $loop++) - { - $current_day = date("Y-m-d", mktime(0, 0, 1, $parts[1], $parts[2]+$loop, $parts[0])); - if($current_day <= $a_to) - { - $data[$current_day] = (float)$raw[$current_day]; - } - } - - return $data; - } - - protected function getListData() - { - $data = array(); - - $today = date("Y-m-d"); - $yesterday = date("Y-m-d", strtotime("yesterday")); - - $all = $this->page_id - ? ilWikiStat::getFigureOptionsPage() - : ilWikiStat::getFigureOptions(); - foreach($all as $figure => $title) - { - if($this->page_id) - { - $tmp = (array)ilWikiStat::getFigureDataPage($this->wiki_id, $this->page_id, $figure, $yesterday, $today); - } - else - { - $tmp = (array)ilWikiStat::getFigureData($this->wiki_id, $figure, $yesterday, $today); - } - $data[$title] = array( - "yesterday" => (float)$tmp[$yesterday], - "today" => (float)$tmp[$today] - ); - } - - return $data; - } - - protected function renderGraph($a_figure, array $a_data) - { - $scope = ceil(sizeof($a_data)/31); - - include_once "Services/Chart/classes/class.ilChartGrid.php"; - $chart = ilChart::getInstanceByType(ilChart::TYPE_GRID, "wikistat"); - $chart->setSize("100%", 400); - $chart->setColors(array("#C0E0FF")); - - $legend = new ilChartLegend(); - $chart->setLegend($legend); - - // lines vs. bars - if(in_array($a_figure, array( - // wiki - ilWikiStat::KEY_FIGURE_WIKI_NUM_PAGES - ,ilWikiStat::KEY_FIGURE_WIKI_INTERNAL_LINKS - ,ilWikiStat::KEY_FIGURE_WIKI_INTERNAL_LINKS_AVG - ,ilWikiStat::KEY_FIGURE_WIKI_EXTERNAL_LINKS - ,ilWikiStat::KEY_FIGURE_WIKI_EXTERNAL_LINKS_AVG - ,ilWikiStat::KEY_FIGURE_WIKI_WORDS - ,ilWikiStat::KEY_FIGURE_WIKI_WORDS_AVG - ,ilWikiStat::KEY_FIGURE_WIKI_CHARS - ,ilWikiStat::KEY_FIGURE_WIKI_CHARS_AVG - ,ilWikiStat::KEY_FIGURE_WIKI_FOOTNOTES - ,ilWikiStat::KEY_FIGURE_WIKI_FOOTNOTES_AVG - ,ilWikiStat::KEY_FIGURE_WIKI_RATING_AVG - // page - ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_INTERNAL_LINKS - ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_EXTERNAL_LINKS - ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_WORDS - ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_CHARS - ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_FOOTNOTES - ))) - { - $series = $chart->getDataInstance(ilChartGrid::DATA_LINES); - $series->setLineSteps(true); - $series->setFill(true, "#E0F0FF"); - } - else - { - $series = $chart->getDataInstance(ilChartGrid::DATA_BARS); - $series->setBarOptions(round(10/($scope*2))/10); - } - $series->setLabel(ilWikiStat::getFigureTitle($a_figure)); - - $labels = array(); - $x = 0; - foreach($a_data as $date => $value) - { - $series->addPoint($x, $value); - - $day = (int)substr($date, 8, 2); - - // match scale to scope - if($scope == 1) - { - // daily - $labels[$x] = substr($date, 8, 2); - } - elseif($scope == 2) - { - // weekly - if(!($x%7)) - { - $labels[$x] = substr($date, 8, 2).".".substr($date, 5, 2)."."; - } - } - else - { - // 1st/15th - if($day == 1 || $day == 15 || $x == sizeof($a_data)-1) - { - $labels[$x] = substr($date, 8, 2).".".substr($date, 5, 2)."."; - } - } - - $x++; - } - - $chart->addData($series); - $chart->setTicks($labels, null, true); - - // int vs. float (averages) - if(in_array($a_figure, array( - // wiki - ilWikiStat::KEY_FIGURE_WIKI_NUM_PAGES - ,ilWikiStat::KEY_FIGURE_WIKI_NEW_PAGES - ,ilWikiStat::KEY_FIGURE_WIKI_EDIT_PAGES - ,ilWikiStat::KEY_FIGURE_WIKI_DELETED_PAGES - ,ilWikiStat::KEY_FIGURE_WIKI_READ_PAGES - ,ilWikiStat::KEY_FIGURE_WIKI_USER_EDIT_PAGES - ,ilWikiStat::KEY_FIGURE_WIKI_NUM_RATING - ,ilWikiStat::KEY_FIGURE_WIKI_INTERNAL_LINKS - ,ilWikiStat::KEY_FIGURE_WIKI_EXTERNAL_LINKS - ,ilWikiStat::KEY_FIGURE_WIKI_WORDS - ,ilWikiStat::KEY_FIGURE_WIKI_CHARS - ,ilWikiStat::KEY_FIGURE_WIKI_FOOTNOTES - // page - ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_CHANGES - ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_USER_EDIT - ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_READ - ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_INTERNAL_LINKS - ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_EXTERNAL_LINKS - ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_WORDS - ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_CHARS - ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_FOOTNOTES - ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_RATINGS - ))) - { - $chart->setYAxisToInteger(true); - } - - return $chart->getHTML(); - } -} - -?> \ No newline at end of file + /** + * @var ilLanguage + */ + protected $lng; + + /** + * @var ilTemplate + */ + protected $tpl; + + protected $wiki_id; // [integer] + protected $page_id; // [integer] + + public function __construct($a_wiki_id, $a_page_id = null) + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->toolbar = $DIC->toolbar(); + $this->lng = $DIC->language(); + $this->tpl = $DIC["tpl"]; + $this->wiki_id = (int) $a_wiki_id; + $this->page_id = (int) $a_page_id; + } + + public function executeCommand() + { + $ilCtrl = $this->ctrl; + + $next_class = $ilCtrl->getNextClass($this); + $cmd = $ilCtrl->getCmd("view"); + + switch ($next_class) { + default: + $this->$cmd(); + break; + } + } + + protected function viewToolbar($a_is_initial = false) + { + $ilToolbar = $this->toolbar; + $lng = $this->lng; + $ilCtrl = $this->ctrl; + + $current_figure = (int) $_POST["fig"]; + $current_time_frame = (string) $_POST["tfr"]; + $current_scope = (int) $_POST["scp"]; + + include_once "Services/Form/classes/class.ilPropertyFormGUI.php"; + $view = new ilSelectInputGUI($lng->txt("wiki_stat_figure"), "fig"); + $view->setOptions($this->page_id + ? ilWikiStat::getFigureOptionsPage() + : ilWikiStat::getFigureOptions()); + if ($current_figure) { + $view->setValue($current_figure); + } elseif ($a_is_initial) { + // default + $current_figure = $this->page_id + ? ilWikiStat::KEY_FIGURE_WIKI_PAGE_CHANGES + : ilWikiStat::KEY_FIGURE_WIKI_NUM_PAGES; + } + $ilToolbar->addInputItem($view, true); + + $options = array(); + include_once "Services/Calendar/classes/class.ilCalendarUtil.php"; + $lng->loadLanguageModule("dateplaner"); + foreach (ilWikiStat::getAvailableMonths($this->wiki_id) as $month) { + $parts = explode("-", $month); + $options[$month] = ilCalendarUtil::_numericMonthToString((int) $parts[1]) . + " " . $parts[0]; + } + krsort($options); + + $tframe = new ilSelectInputGUI($lng->txt("month"), "tfr"); + $tframe->setOptions($options); + if ($current_time_frame) { + $tframe->setValue($current_time_frame); + } elseif ($a_is_initial) { + $current_time_frame = array_shift(array_keys($options)); // default + } + $ilToolbar->addInputItem($tframe, true); + + $scope = new ilSelectInputGUI($lng->txt("wiki_stat_scope"), "scp"); + $scope->setOptions(array( + 1 => "1 " . $lng->txt("month"), + 2 => "2 " . $lng->txt("months"), + 3 => "3 " . $lng->txt("months"), + 4 => "4 " . $lng->txt("months"), + 5 => "5 " . $lng->txt("months"), + 6 => "6 " . $lng->txt("months") + )); + if ($current_scope) { + $scope->setValue($current_scope); + } elseif ($a_is_initial) { + $current_scope = 1; // default + } + $ilToolbar->addInputItem($scope, true); + + $ilToolbar->setFormAction($ilCtrl->getFormAction($this, "view")); + $ilToolbar->addFormButton($lng->txt("show"), "view"); + + if ($current_figure && $current_time_frame && $current_scope) { + $ilToolbar->addSeparator(); + $ilToolbar->addFormButton($lng->txt("export"), "export"); + + return array( + "figure" => $current_figure, + "month" => $current_time_frame, + "scope" => $current_scope + ); + } + } + + protected function export() + { + $ilCtrl = $this->ctrl; + + $params = $this->viewToolbar(); + if ($params) { + // data + + $tfr = explode("-", (string) $params["month"]); + $day_from = date("Y-m-d", mktime(0, 0, 1, $tfr[1]-($params["scope"]-1), 1, $tfr[0])); + $day_to = date("Y-m-d", mktime(0, 0, 1, $tfr[1]+1, 0, $tfr[0])); + unset($tfr); + + $chart_data = $this->getChartData($params["figure"], $params["scope"], $day_from, $day_to); + + + // excel + + $period = ilDatePresentation::formatPeriod( + new ilDate($day_from, IL_CAL_DATE), + new ilDate($day_to, IL_CAL_DATE) + ); + + $filename = ilObject::_lookupTitle($this->wiki_id); + if ($this->page_id) { + $filename .= " - " . ilWikiPage::lookupTitle($this->page_id); + } + $filename .= " - " . ilWikiStat::getFigureTitle($params["figure"]) . " - " . $period; + + include_once "./Services/Excel/classes/class.ilExcel.php"; + $excel = new ilExcel(); + $excel->addSheet($this->lng->txt("statistics")); + + $row = 1; + foreach ($chart_data as $day => $value) { + $excel->setCell($row, 0, $day); + $excel->setCell($row++, 1, $value); + } + + $excel->sendToClient($filename); + } + + $ilCtrl->redirect($this, "view"); + } + + protected function initial() + { + $this->view(true); + } + + protected function view($a_is_initial = false) + { + $tpl = $this->tpl; + $lng = $this->lng; + + $params = $this->viewToolbar($a_is_initial); + if (is_array($params)) { + // data + + $tfr = explode("-", (string) $params["month"]); + $day_from = date("Y-m-d", mktime(0, 0, 1, $tfr[1]-($params["scope"]-1), 1, $tfr[0])); + $day_to = date("Y-m-d", mktime(0, 0, 1, $tfr[1]+1, 0, $tfr[0])); + unset($tfr); + + $chart_data = $this->getChartData($params["figure"], $params["scope"], $day_from, $day_to); + $list_data = $this->getListData(); + + + // render + + $vtpl = new ilTemplate("tpl.wiki_stat_list.html", true, true, "Modules/Wiki"); + + include_once("./Services/UIComponent/Panel/classes/class.ilPanelGUI.php"); + $chart_panel = ilPanelGUI::getInstance(); + + $vtpl->setVariable("CHART", $this->renderGraph($params["figure"], $chart_data)); + + $vtpl->setCurrentBlock("row_bl"); + $counter = 0; + foreach ($list_data as $figure => $values) { + $day = (int) substr($day, 8); + $vtpl->setVariable("CSS_ROW", ($counter++%2) ? "tblrow1" : "tblrow2"); + $vtpl->setVariable("FIGURE", $figure); + $vtpl->setVariable("YESTERDAY_VALUE", $values["yesterday"]); + $vtpl->setVariable("TODAY_VALUE", $values["today"]); + $vtpl->parseCurrentBlock(); + } + + $vtpl->setVariable("FIGURE_HEAD", $lng->txt("wiki_stat_figure")); + $vtpl->setVariable("YESTERDAY_HEAD", $lng->txt("yesterday")); + $vtpl->setVariable("TODAY_HEAD", $lng->txt("today")); + + $chart_panel->setHeading($lng->txt("statistics")); + $chart_panel->setBody($vtpl->get()); + $chart_panel->setHeadingStyle(ilPanelGUI::HEADING_STYLE_SUBHEADING); + + $tpl->setContent($chart_panel->getHTML()); + } + } + + protected function getChartData($a_figure, $a_scope, $a_from, $a_to) + { + $data = array(); + + $raw = $this->page_id + ? ilWikiStat::getFigureDataPage($this->wiki_id, $this->page_id, $a_figure, $a_from, $a_to) + : ilWikiStat::getFigureData($this->wiki_id, $a_figure, $a_from, $a_to); + + $parts = explode("-", $a_from); + for ($loop = 0; $loop <= ($a_scope*31); $loop++) { + $current_day = date("Y-m-d", mktime(0, 0, 1, $parts[1], $parts[2]+$loop, $parts[0])); + if ($current_day <= $a_to) { + $data[$current_day] = (float) $raw[$current_day]; + } + } + + return $data; + } + + protected function getListData() + { + $data = array(); + + $today = date("Y-m-d"); + $yesterday = date("Y-m-d", strtotime("yesterday")); + + $all = $this->page_id + ? ilWikiStat::getFigureOptionsPage() + : ilWikiStat::getFigureOptions(); + foreach ($all as $figure => $title) { + if ($this->page_id) { + $tmp = (array) ilWikiStat::getFigureDataPage($this->wiki_id, $this->page_id, $figure, $yesterday, $today); + } else { + $tmp = (array) ilWikiStat::getFigureData($this->wiki_id, $figure, $yesterday, $today); + } + $data[$title] = array( + "yesterday" => (float) $tmp[$yesterday], + "today" => (float) $tmp[$today] + ); + } + + return $data; + } + + protected function renderGraph($a_figure, array $a_data) + { + $scope = ceil(sizeof($a_data)/31); + + include_once "Services/Chart/classes/class.ilChartGrid.php"; + $chart = ilChart::getInstanceByType(ilChart::TYPE_GRID, "wikistat"); + $chart->setSize("100%", 400); + $chart->setColors(array("#C0E0FF")); + + $legend = new ilChartLegend(); + $chart->setLegend($legend); + + // lines vs. bars + if (in_array($a_figure, array( + // wiki + ilWikiStat::KEY_FIGURE_WIKI_NUM_PAGES + ,ilWikiStat::KEY_FIGURE_WIKI_INTERNAL_LINKS + ,ilWikiStat::KEY_FIGURE_WIKI_INTERNAL_LINKS_AVG + ,ilWikiStat::KEY_FIGURE_WIKI_EXTERNAL_LINKS + ,ilWikiStat::KEY_FIGURE_WIKI_EXTERNAL_LINKS_AVG + ,ilWikiStat::KEY_FIGURE_WIKI_WORDS + ,ilWikiStat::KEY_FIGURE_WIKI_WORDS_AVG + ,ilWikiStat::KEY_FIGURE_WIKI_CHARS + ,ilWikiStat::KEY_FIGURE_WIKI_CHARS_AVG + ,ilWikiStat::KEY_FIGURE_WIKI_FOOTNOTES + ,ilWikiStat::KEY_FIGURE_WIKI_FOOTNOTES_AVG + ,ilWikiStat::KEY_FIGURE_WIKI_RATING_AVG + // page + ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_INTERNAL_LINKS + ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_EXTERNAL_LINKS + ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_WORDS + ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_CHARS + ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_FOOTNOTES + ))) { + $series = $chart->getDataInstance(ilChartGrid::DATA_LINES); + $series->setLineSteps(true); + $series->setFill(true, "#E0F0FF"); + } else { + $series = $chart->getDataInstance(ilChartGrid::DATA_BARS); + $series->setBarOptions(round(10/($scope*2))/10); + } + $series->setLabel(ilWikiStat::getFigureTitle($a_figure)); + + $labels = array(); + $x = 0; + foreach ($a_data as $date => $value) { + $series->addPoint($x, $value); + + $day = (int) substr($date, 8, 2); + + // match scale to scope + if ($scope == 1) { + // daily + $labels[$x] = substr($date, 8, 2); + } elseif ($scope == 2) { + // weekly + if (!($x%7)) { + $labels[$x] = substr($date, 8, 2) . "." . substr($date, 5, 2) . "."; + } + } else { + // 1st/15th + if ($day == 1 || $day == 15 || $x == sizeof($a_data)-1) { + $labels[$x] = substr($date, 8, 2) . "." . substr($date, 5, 2) . "."; + } + } + + $x++; + } + + $chart->addData($series); + $chart->setTicks($labels, null, true); + + // int vs. float (averages) + if (in_array($a_figure, array( + // wiki + ilWikiStat::KEY_FIGURE_WIKI_NUM_PAGES + ,ilWikiStat::KEY_FIGURE_WIKI_NEW_PAGES + ,ilWikiStat::KEY_FIGURE_WIKI_EDIT_PAGES + ,ilWikiStat::KEY_FIGURE_WIKI_DELETED_PAGES + ,ilWikiStat::KEY_FIGURE_WIKI_READ_PAGES + ,ilWikiStat::KEY_FIGURE_WIKI_USER_EDIT_PAGES + ,ilWikiStat::KEY_FIGURE_WIKI_NUM_RATING + ,ilWikiStat::KEY_FIGURE_WIKI_INTERNAL_LINKS + ,ilWikiStat::KEY_FIGURE_WIKI_EXTERNAL_LINKS + ,ilWikiStat::KEY_FIGURE_WIKI_WORDS + ,ilWikiStat::KEY_FIGURE_WIKI_CHARS + ,ilWikiStat::KEY_FIGURE_WIKI_FOOTNOTES + // page + ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_CHANGES + ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_USER_EDIT + ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_READ + ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_INTERNAL_LINKS + ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_EXTERNAL_LINKS + ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_WORDS + ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_CHARS + ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_FOOTNOTES + ,ilWikiStat::KEY_FIGURE_WIKI_PAGE_RATINGS + ))) { + $chart->setYAxisToInteger(true); + } + + return $chart->getHTML(); + } +} diff --git a/Modules/Wiki/classes/class.ilWikiUserHTMLExport.php b/Modules/Wiki/classes/class.ilWikiUserHTMLExport.php index 631511f0a4b9ce3c486fc6b6c64ade12bd2dd0fd..8277ffe3a7787a24370def887612da10b87728ee 100644 --- a/Modules/Wiki/classes/class.ilWikiUserHTMLExport.php +++ b/Modules/Wiki/classes/class.ilWikiUserHTMLExport.php @@ -7,226 +7,219 @@ * * @author Alex Killing'.$lng->txt("copg_snippet_cannot_be_edited").$info.'
'.$html; - } - } - else - { - if ($a_mode == "edit") - { - if ($param[2] <= 0) - { - $html = "// ".$lng->txt("cont_missing_snippet")." //"; - } - else - { - $html = "// ".$lng->txt("cont_snippet_from_another_installation")." //"; - } - } - } - $h2 = substr($a_html, 0, $start). - $html. - substr($a_html, $end + 5); - $a_html = $h2; - $i++; - } - - $start = strpos($a_html, "{{{{{ContentInclude;", $start + 5); - $end = 0; - if (is_int($start)) - { - $end = strpos($a_html, "}}}}}", $start); - } - } - return $a_html; - } + $html = $page_gui->getRawContent(); + if ($a_mode == "edit") { + include_once("./Services/Link/classes/class.ilLink.php"); + $par_id = $page_gui->getPageObject()->getParentId(); + $info = ""; + foreach (ilObject::_getAllReferences($par_id) as $ref_id) { + if ($this->access->checkAccess("write", "", $ref_id)) { + $info = " " . $lng->txt("title") . ": " . ilMediaPoolItem::lookupTitle($page_gui->getPageObject()->getId()) . + ", " . $lng->txt("obj_mep") . ": " . ilObject::_lookupTitle($par_id) . ""; + } + } + $html = '' . $lng->txt("copg_snippet_cannot_be_edited") . $info . '
' . $html; + } + } else { + if ($a_mode == "edit") { + if ($param[2] <= 0) { + $html = "// " . $lng->txt("cont_missing_snippet") . " //"; + } else { + $html = "// " . $lng->txt("cont_snippet_from_another_installation") . " //"; + } + } + } + $h2 = substr($a_html, 0, $start) . + $html . + substr($a_html, $end + 5); + $a_html = $h2; + $i++; + } + $start = strpos($a_html, "{{{{{ContentInclude;", $start + 5); + $end = 0; + if (is_int($start)) { + $end = strpos($a_html, "}}}}}", $start); + } + } + return $a_html; + } } - -?> \ No newline at end of file diff --git a/Services/COPage/classes/class.ilPCContentIncludeGUI.php b/Services/COPage/classes/class.ilPCContentIncludeGUI.php index 057e3dd6c66e677417ffd01f2f8ac38163183225..6bb897ed1e60a4f8fef788572de8b921b6a6ea94 100644 --- a/Services/COPage/classes/class.ilPCContentIncludeGUI.php +++ b/Services/COPage/classes/class.ilPCContentIncludeGUI.php @@ -16,187 +16,182 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); */ class ilPCContentIncludeGUI extends ilPageContentGUI { - /** - * @var ilAccessHandler - */ - protected $access; - - /** - * @var ilTabsGUI - */ - protected $tabs; - - - /** - * Constructor - * @access public - */ - function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") - { - global $DIC; - - $this->ctrl = $DIC->ctrl(); - $this->access = $DIC->access(); - $this->tabs = $DIC->tabs(); - $this->tpl = $DIC["tpl"]; - $this->lng = $DIC->language(); - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - } - - /** - * execute command - */ - function executeCommand() - { - // get next class that processes or forwards current command - $next_class = $this->ctrl->getNextClass($this); - - // get current command - $cmd = $this->ctrl->getCmd(); - - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } - - return $ret; - } - - /** - * Insert new resources component form. - */ - function insert() - { - switch ($_GET["subCmd"]) - { - case "selectPool": - $this->selectPool(); - break; - - case "poolSelection": - $this->poolSelection(); - break; - - default: - $this->insertFromPool($a_post_cmd, $a_submit_cmd); - break; - } - } - - /** - * Insert page snippet from media pool - */ - function insertFromPool($a_post_cmd = "edpost", $a_submit_cmd = "create_mob") - { - $ilCtrl = $this->ctrl; - $ilAccess = $this->access; - $ilTabs = $this->tabs; - $tpl = $this->tpl; - $lng = $this->lng; - - - if ($_SESSION["cont_media_pool"] != "" && - $ilAccess->checkAccess("write", "", $_SESSION["cont_media_pool"]) - && ilObject::_lookupType(ilObject::_lookupObjId($_SESSION["cont_media_pool"])) == "mep") - { - $html = ""; - $tb = new ilToolbarGUI(); - - $ilCtrl->setParameter($this, "subCmd", "poolSelection"); - - $tb->addButton($lng->txt("cont_select_media_pool"), - $ilCtrl->getLinkTarget($this, "insert")); - $html = $tb->getHTML(); - - $ilCtrl->setParameter($this, "subCmd", ""); - - include_once("./Modules/MediaPool/classes/class.ilObjMediaPool.php"); - include_once("./Modules/MediaPool/classes/class.ilMediaPoolTableGUI.php"); - $pool = new ilObjMediaPool($_SESSION["cont_media_pool"]); - $ilCtrl->setParameter($this, "subCmd", "insertFromPool"); - $mpool_table = new ilMediaPoolTableGUI($this, "insert", $pool, "mep_folder", - ilMediaPoolTableGUI::IL_MEP_SELECT_CONTENT); - $mpool_table->setInsertCommand("create_incl"); - - $html.= $mpool_table->getHTML(); - - $tpl->setContent($html); - } - else - { - $this->poolSelection(); - } - } - - /** - * Pool Selection - */ - function poolSelection() - { - $tpl = $this->tpl; - $ilCtrl = $this->ctrl; - -// $this->getTabs($ilTabs, true); -// $ilTabs->setSubTabActive("cont_mob_from_media_pool"); - - include_once "./Services/COPage/classes/class.ilPoolSelectorGUI.php"; - $ilCtrl->setParameter($this, "subCmd", "poolSelection"); - $exp = new ilPoolSelectorGUI($this, "insert"); - - // filter - $exp->setTypeWhiteList(array("root", "cat", "grp", "fold", "crs", "mep")); - $exp->setClickableTypes(array('mep')); - - if (!$exp->handleCommand()) - { - $tpl->setContent($exp->getHTML()); - } - } - - /** - * create new content include in dom and update page in db - */ - function create() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - if (is_array($_POST["id"])) - { - for($i = count($_POST["id"]) - 1; $i>=0; $i--) - { - // similar code in ilpageeditorgui::insertFromClipboard - include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); - include_once("./Services/COPage/classes/class.ilPCMediaObject.php"); - $this->content_obj = new ilPCContentInclude($this->getPage()); - $this->content_obj->create($this->pg_obj, $_GET["hier_id"], $this->pc_id); - $this->content_obj->setContentType("mep"); - $this->content_obj->setContentId($_POST["id"][$i]); - } - $this->updated = $this->pg_obj->update(); - } - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - } - else - { - $this->insert(); - } - } - - /** - * Select concrete pool - */ - function selectPool() - { - $ilCtrl = $this->ctrl; - - $_SESSION["cont_media_pool"] = $_GET["pool_ref_id"]; - $ilCtrl->setParameter($this, "subCmd", "insertFromPool"); - $ilCtrl->redirect($this, "insert"); - } + /** + * @var ilAccessHandler + */ + protected $access; + + /** + * @var ilTabsGUI + */ + protected $tabs; + + + /** + * Constructor + * @access public + */ + public function __construct(&$a_pg_obj, &$a_content_obj, $a_hier_id, $a_pc_id = "") + { + global $DIC; + + $this->ctrl = $DIC->ctrl(); + $this->access = $DIC->access(); + $this->tabs = $DIC->tabs(); + $this->tpl = $DIC["tpl"]; + $this->lng = $DIC->language(); + parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); + } + + /** + * execute command + */ + public function executeCommand() + { + // get next class that processes or forwards current command + $next_class = $this->ctrl->getNextClass($this); + + // get current command + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } + + return $ret; + } + + /** + * Insert new resources component form. + */ + public function insert() + { + switch ($_GET["subCmd"]) { + case "selectPool": + $this->selectPool(); + break; + + case "poolSelection": + $this->poolSelection(); + break; + + default: + $this->insertFromPool($a_post_cmd, $a_submit_cmd); + break; + } + } + + /** + * Insert page snippet from media pool + */ + public function insertFromPool($a_post_cmd = "edpost", $a_submit_cmd = "create_mob") + { + $ilCtrl = $this->ctrl; + $ilAccess = $this->access; + $ilTabs = $this->tabs; + $tpl = $this->tpl; + $lng = $this->lng; + + + if ($_SESSION["cont_media_pool"] != "" && + $ilAccess->checkAccess("write", "", $_SESSION["cont_media_pool"]) + && ilObject::_lookupType(ilObject::_lookupObjId($_SESSION["cont_media_pool"])) == "mep") { + $html = ""; + $tb = new ilToolbarGUI(); + + $ilCtrl->setParameter($this, "subCmd", "poolSelection"); + + $tb->addButton( + $lng->txt("cont_select_media_pool"), + $ilCtrl->getLinkTarget($this, "insert") + ); + $html = $tb->getHTML(); + + $ilCtrl->setParameter($this, "subCmd", ""); + + include_once("./Modules/MediaPool/classes/class.ilObjMediaPool.php"); + include_once("./Modules/MediaPool/classes/class.ilMediaPoolTableGUI.php"); + $pool = new ilObjMediaPool($_SESSION["cont_media_pool"]); + $ilCtrl->setParameter($this, "subCmd", "insertFromPool"); + $mpool_table = new ilMediaPoolTableGUI( + $this, + "insert", + $pool, + "mep_folder", + ilMediaPoolTableGUI::IL_MEP_SELECT_CONTENT + ); + $mpool_table->setInsertCommand("create_incl"); + + $html.= $mpool_table->getHTML(); + + $tpl->setContent($html); + } else { + $this->poolSelection(); + } + } + + /** + * Pool Selection + */ + public function poolSelection() + { + $tpl = $this->tpl; + $ilCtrl = $this->ctrl; + + // $this->getTabs($ilTabs, true); + // $ilTabs->setSubTabActive("cont_mob_from_media_pool"); + + include_once "./Services/COPage/classes/class.ilPoolSelectorGUI.php"; + $ilCtrl->setParameter($this, "subCmd", "poolSelection"); + $exp = new ilPoolSelectorGUI($this, "insert"); + + // filter + $exp->setTypeWhiteList(array("root", "cat", "grp", "fold", "crs", "mep")); + $exp->setClickableTypes(array('mep')); + + if (!$exp->handleCommand()) { + $tpl->setContent($exp->getHTML()); + } + } + + /** + * create new content include in dom and update page in db + */ + public function create() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + if (is_array($_POST["id"])) { + for ($i = count($_POST["id"]) - 1; $i>=0; $i--) { + // similar code in ilpageeditorgui::insertFromClipboard + include_once("./Modules/MediaPool/classes/class.ilMediaPoolItem.php"); + include_once("./Services/COPage/classes/class.ilPCMediaObject.php"); + $this->content_obj = new ilPCContentInclude($this->getPage()); + $this->content_obj->create($this->pg_obj, $_GET["hier_id"], $this->pc_id); + $this->content_obj->setContentType("mep"); + $this->content_obj->setContentId($_POST["id"][$i]); + } + $this->updated = $this->pg_obj->update(); + } + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + } else { + $this->insert(); + } + } + + /** + * Select concrete pool + */ + public function selectPool() + { + $ilCtrl = $this->ctrl; + + $_SESSION["cont_media_pool"] = $_GET["pool_ref_id"]; + $ilCtrl->setParameter($this, "subCmd", "insertFromPool"); + $ilCtrl->redirect($this, "insert"); + } } -?> diff --git a/Services/COPage/classes/class.ilPCContentTemplate.php b/Services/COPage/classes/class.ilPCContentTemplate.php index b55afe15c2a654caaa2d8b93ac41e324073bd244..766c9416f475cdb9af87dfba46a1060cd11e4a1c 100755 --- a/Services/COPage/classes/class.ilPCContentTemplate.php +++ b/Services/COPage/classes/class.ilPCContentTemplate.php @@ -15,114 +15,98 @@ require_once("./Services/COPage/classes/class.ilPageContent.php"); */ class ilPCContentTemplate extends ilPageContent { - /** - * Init page content component. - */ - function init() - { - $this->setType("templ"); - } - - /** - * Set node (in fact this will never be called, since these types of nodes do not exist - */ - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - } - - /** - * Insert content template - * - * @param ilPageObject $a_pg_obj page object - * @param string $a_hier_id Hierarchical ID - * @param string $a_pc_id pc id - * @param int $a_page_templ template page id - */ - function create($a_pg_obj, $a_hier_id, $a_pc_id, $a_page_templ) - { - $source_id = explode(":", $a_page_templ); - $source_page = ilPageObjectFactory::getInstance($source_id[1], $source_id[0]); - $source_page->buildDom(); - $source_page->addHierIds(); - $hier_ids = $source_page->getHierIds(); - - $copy_ids = array(); - foreach ($hier_ids as $hier_id) - { - // move top level nodes only - if (!is_int(strpos($hier_id, "_"))) - { - if ($hier_id != "pg" && $hier_id >= $a_hid) - { - $copy_ids[] = $hier_id; - } - } - } - asort($copy_ids); - - // get the target parent node - $pos = explode("_", $a_pos); - array_pop($pos); - $parent_pos = implode($pos, "_"); - if($parent_pos != "") - { - $target_parent = $a_pg_obj->getContentNode($parent_pos); - } - else - { - $target_parent = $a_pg_obj->getNode(); - } - - //$source_parent = $source_page->getContentNode("pg"); - - $curr_node = $a_pg_obj->getContentNode($a_hier_id, $a_pcid); - - foreach ($copy_ids as $copy_id) - { - $source_node = $source_page->getContentNode($copy_id); - $new_node = $source_node->clone_node(true); - $new_node->unlink_node($new_node); - - if ($succ_node = $curr_node->next_sibling()) - { - $succ_node->insert_before($new_node, $succ_node); - } - else - { -//echo "movin doin append_child"; - $target_parent->append_child($new_node); - } - - //$xpc = xpath_new_context($a_pg_obj->getDomDoc()); - $xpath = new DOMXpath($a_pg_obj->getDomDoc()); -//var_dump($new_node->myDOMNode); -//echo "-".$new_node->get_attribute("PCID")."-"; exit; - if ($new_node->get_attribute("PCID") != "") - { - $new_node->set_attribute("PCID", ""); - } - $els = $xpath->query(".//*[@PCID]", $new_node->myDOMNode); - foreach ($els as $el) - { - $el->setAttribute("PCID", ""); - } - $curr_node = $new_node; - } - - $a_pg_obj->update(); - - //$this->node = $this->createPageContentNode(); - - /*$a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER, $a_pc_id); - $this->map_node =& $this->dom->create_element("Map"); - $this->map_node =& $this->node->append_child($this->map_node); - $this->map_node->set_attribute("Latitude", "0"); - $this->map_node->set_attribute("Longitude", "0"); - $this->map_node->set_attribute("Zoom", "3");*/ - } - - + /** + * Init page content component. + */ + public function init() + { + $this->setType("templ"); + } + + /** + * Set node (in fact this will never be called, since these types of nodes do not exist + */ + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + } + + /** + * Insert content template + * + * @param ilPageObject $a_pg_obj page object + * @param string $a_hier_id Hierarchical ID + * @param string $a_pc_id pc id + * @param int $a_page_templ template page id + */ + public function create($a_pg_obj, $a_hier_id, $a_pc_id, $a_page_templ) + { + $source_id = explode(":", $a_page_templ); + $source_page = ilPageObjectFactory::getInstance($source_id[1], $source_id[0]); + $source_page->buildDom(); + $source_page->addHierIds(); + $hier_ids = $source_page->getHierIds(); + + $copy_ids = array(); + foreach ($hier_ids as $hier_id) { + // move top level nodes only + if (!is_int(strpos($hier_id, "_"))) { + if ($hier_id != "pg" && $hier_id >= $a_hid) { + $copy_ids[] = $hier_id; + } + } + } + asort($copy_ids); + + // get the target parent node + $pos = explode("_", $a_pos); + array_pop($pos); + $parent_pos = implode($pos, "_"); + if ($parent_pos != "") { + $target_parent = $a_pg_obj->getContentNode($parent_pos); + } else { + $target_parent = $a_pg_obj->getNode(); + } + + //$source_parent = $source_page->getContentNode("pg"); + + $curr_node = $a_pg_obj->getContentNode($a_hier_id, $a_pcid); + + foreach ($copy_ids as $copy_id) { + $source_node = $source_page->getContentNode($copy_id); + $new_node = $source_node->clone_node(true); + $new_node->unlink_node($new_node); + + if ($succ_node = $curr_node->next_sibling()) { + $succ_node->insert_before($new_node, $succ_node); + } else { + //echo "movin doin append_child"; + $target_parent->append_child($new_node); + } + + //$xpc = xpath_new_context($a_pg_obj->getDomDoc()); + $xpath = new DOMXpath($a_pg_obj->getDomDoc()); + //var_dump($new_node->myDOMNode); + //echo "-".$new_node->get_attribute("PCID")."-"; exit; + if ($new_node->get_attribute("PCID") != "") { + $new_node->set_attribute("PCID", ""); + } + $els = $xpath->query(".//*[@PCID]", $new_node->myDOMNode); + foreach ($els as $el) { + $el->setAttribute("PCID", ""); + } + $curr_node = $new_node; + } + + $a_pg_obj->update(); + + //$this->node = $this->createPageContentNode(); + + /*$a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER, $a_pc_id); + $this->map_node =& $this->dom->create_element("Map"); + $this->map_node =& $this->node->append_child($this->map_node); + $this->map_node->set_attribute("Latitude", "0"); + $this->map_node->set_attribute("Longitude", "0"); + $this->map_node->set_attribute("Zoom", "3");*/ + } } - -?> diff --git a/Services/COPage/classes/class.ilPCContentTemplateGUI.php b/Services/COPage/classes/class.ilPCContentTemplateGUI.php index 65108749a8a09b6a5fed96260030f6a9e183c9b4..373b73d5ce63e03a841867922987c57fa86983ff 100755 --- a/Services/COPage/classes/class.ilPCContentTemplateGUI.php +++ b/Services/COPage/classes/class.ilPCContentTemplateGUI.php @@ -20,109 +20,107 @@ require_once("./Services/COPage/classes/class.ilPageContentGUI.php"); class ilPCContentTemplateGUI extends ilPageContentGUI { - /** - * Constructor - */ - function __construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id = "") - { - global $DIC; - - $this->tpl = $DIC["tpl"]; - $this->ctrl = $DIC->ctrl(); - $this->lng = $DIC->language(); - parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); - } - - /** - * Execute command - */ - function executeCommand() - { - // get next class that processes or forwards current command - $next_class = $this->ctrl->getNextClass($this); - - // get current command - $cmd = $this->ctrl->getCmd(); - - switch($next_class) - { - default: - $ret = $this->$cmd(); - break; - } - - return $ret; - } - - /** - * Insert content template - */ - function insert() - { - $tpl = $this->tpl; - - $this->displayValidationError(); - $form = $this->initForm(); - $tpl->setContent($form->getHTML()); - } - - /** - * Init creation from - */ - function initForm() - { - $ilCtrl = $this->ctrl; - $lng = $this->lng; - - // edit form - include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); - $form = new ilPropertyFormGUI(); - $form->setFormAction($ilCtrl->getFormAction($this)); - $form->setTitle($this->lng->txt("cont_ed_insert_templ")); - - $radg = new ilRadioGroupInputGUI($lng->txt("cont_template"), "page_templ"); - $radg->setRequired(true); - - $ts = $this->getPage()->getContentTemplates(); - foreach ($ts as $t) - { - $op = new ilRadioOption($t["title"], $t["id"].":".$t["parent_type"]); - $radg->addOption($op); - } - - $form->addItem($radg); - - - $form->addCommandButton("create_templ", $lng->txt("insert")); - $form->addCommandButton("cancelCreate", $lng->txt("cancel")); - - return $form; - } - - /** - * Insert the template - */ - function create() - { - $tpl = $this->tpl; - - $form = $this->initForm(); - if ($form->checkInput()) - { - $this->content_obj = new ilPCContentTemplate($this->getPage()); - $this->content_obj->create($this->pg_obj, $this->hier_id, $this->pc_id, - $form->getInput("page_templ")); - $this->updated = $this->pg_obj->update(); - if ($this->updated === true) - { - $this->ctrl->returnToParent($this, "jump".$this->hier_id); - return; - } - } - $this->displayValidationError(); - $form->setValuesByPost(); - $tpl->setContent($form->getHTML()); - } - + /** + * Constructor + */ + public function __construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id = "") + { + global $DIC; + + $this->tpl = $DIC["tpl"]; + $this->ctrl = $DIC->ctrl(); + $this->lng = $DIC->language(); + parent::__construct($a_pg_obj, $a_content_obj, $a_hier_id, $a_pc_id); + } + + /** + * Execute command + */ + public function executeCommand() + { + // get next class that processes or forwards current command + $next_class = $this->ctrl->getNextClass($this); + + // get current command + $cmd = $this->ctrl->getCmd(); + + switch ($next_class) { + default: + $ret = $this->$cmd(); + break; + } + + return $ret; + } + + /** + * Insert content template + */ + public function insert() + { + $tpl = $this->tpl; + + $this->displayValidationError(); + $form = $this->initForm(); + $tpl->setContent($form->getHTML()); + } + + /** + * Init creation from + */ + public function initForm() + { + $ilCtrl = $this->ctrl; + $lng = $this->lng; + + // edit form + include_once("./Services/Form/classes/class.ilPropertyFormGUI.php"); + $form = new ilPropertyFormGUI(); + $form->setFormAction($ilCtrl->getFormAction($this)); + $form->setTitle($this->lng->txt("cont_ed_insert_templ")); + + $radg = new ilRadioGroupInputGUI($lng->txt("cont_template"), "page_templ"); + $radg->setRequired(true); + + $ts = $this->getPage()->getContentTemplates(); + foreach ($ts as $t) { + $op = new ilRadioOption($t["title"], $t["id"] . ":" . $t["parent_type"]); + $radg->addOption($op); + } + + $form->addItem($radg); + + + $form->addCommandButton("create_templ", $lng->txt("insert")); + $form->addCommandButton("cancelCreate", $lng->txt("cancel")); + + return $form; + } + + /** + * Insert the template + */ + public function create() + { + $tpl = $this->tpl; + + $form = $this->initForm(); + if ($form->checkInput()) { + $this->content_obj = new ilPCContentTemplate($this->getPage()); + $this->content_obj->create( + $this->pg_obj, + $this->hier_id, + $this->pc_id, + $form->getInput("page_templ") + ); + $this->updated = $this->pg_obj->update(); + if ($this->updated === true) { + $this->ctrl->returnToParent($this, "jump" . $this->hier_id); + return; + } + } + $this->displayValidationError(); + $form->setValuesByPost(); + $tpl->setContent($form->getHTML()); + } } -?> diff --git a/Services/COPage/classes/class.ilPCDataTable.php b/Services/COPage/classes/class.ilPCDataTable.php index 4b826e20fbc7f908ac33fa32807cc4a02a04b9dd..359008b059fe4baed12d81a5eb9cd53a96e411c1 100755 --- a/Services/COPage/classes/class.ilPCDataTable.php +++ b/Services/COPage/classes/class.ilPCDataTable.php @@ -1,24 +1,24 @@ setType("dtab"); - } + /** + * Init page content component. + */ + public function init() + { + $this->setType("dtab"); + } - function setNode($a_node) - { - parent::setNode($a_node); // this is the PageContent node - $this->tab_node = $a_node->first_child(); // this is the Table node - } + public function setNode($a_node) + { + parent::setNode($a_node); // this is the PageContent node + $this->tab_node = $a_node->first_child(); // this is the Table node + } - function create(&$a_pg_obj, $a_hier_id, $a_pc_id = "") - { - $this->node = $this->createPageContentNode(); - $a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER, $a_pc_id); - $this->tab_node = $this->dom->create_element("Table"); - $this->tab_node = $this->node->append_child($this->tab_node); - $this->tab_node->set_attribute("Language", ""); - $this->tab_node->set_attribute("DataTable", "y"); - } - - /** - * Get cell paragraph node of row $i and cell $j - */ - function getCellNode($i, $j) - { - $xpc = xpath_new_context($this->dom); - $path = "//PageContent[@HierId='".$this->getHierId()."']". - "/Table/TableRow[$i+1]/TableData[$j+1]/PageContent[1]/Paragraph[1]"; -//echo "", "
"),
- array("[code]", "[/code]"), $text);
- $text = str_replace(array('', ""),
- array("[sup]", "[/sup]"), $text);
- $text = str_replace(array('', ""),
- array("[sub]", "[/sub]"), $text);
-
- $text = str_replace("
", "", $text);
- $text = str_replace('", "
"),
+ array("[code]", "[/code]"),
+ $text
+ );
+ $text = str_replace(
+ array('', ""),
+ array("[sup]", "[/sup]"),
+ $text
+ );
+ $text = str_replace(
+ array('', ""),
+ array("[sub]", "[/sub]"),
+ $text
+ );
+
+ $text = str_replace("
", "", $text);
+ $text = str_replace('", "
"), $s_text);
-
- // sup
- $s_text = str_replace(array("[sup]", "[/sup]"),
- array('', ""), $s_text);
-
- // sub
- $s_text = str_replace(array("[sub]", "[/sub]"),
- array('', ""), $s_text);
-
- return $s_text;
- }
-
-
- /**
- * Save paragraph by JS call
- *
- * @param
- * @return
- */
- function saveJS()
- {
- $ilCtrl = $this->ctrl;
-
- $this->log->debug("start");
-
- $this->updated = $this->content_obj->saveJS($this->pg_obj,
- $_POST["ajaxform_content"],
- ilUtil::stripSlashes($_POST["ajaxform_char"]),
- ilUtil::stripSlashes($_POST["pc_id_str"]));
-
- $this->log->debug("ilPCParagraphGUI, saveJS: got updated value ".$this->updated);
-
- if ($_POST["quick_save"])
- {
- if ($this->updated === true)
- {
- $a_pc_id_str = $this->content_obj->getLastSavedPcId($this->pg_obj, true);
- $this->log->debug("ilPCParagraphGUI, saveJS: echoing pc_id_str ".$a_pc_id_str." (and exit)");
- echo $a_pc_id_str;
- exit;
- }
- }
-
- if ($this->updated !== true && is_array($this->updated))
- {
- $this->outputError($this->updated);
- }
-
- $a_pc_id_str = $this->content_obj->getLastSavedPcId($this->pg_obj, true);
-
- $ilCtrl->setParameterByClass($ilCtrl->getReturnClass($this), "updated_pc_id_str",
- urlencode($a_pc_id_str));
- $this->log->debug("ilPCParagraphGUI, saveJS: redirecting to edit command of ".$ilCtrl->getReturnClass($this).".");
- $ilCtrl->redirectByClass($ilCtrl->getReturnClass($this), "edit", "", true);
- }
-
- /**
- * Output error
- *
- * @param array $a_err error array
- */
- function outputError($a_err)
- {
- $err_str = "";
- foreach ($a_err as $err)
- {
- $err_str.= $err[1]."", "
"),
+ $s_text
+ );
+
+ // sup
+ $s_text = str_replace(
+ array("[sup]", "[/sup]"),
+ array('', ""),
+ $s_text
+ );
+
+ // sub
+ $s_text = str_replace(
+ array("[sub]", "[/sub]"),
+ array('', ""),
+ $s_text
+ );
+
+ return $s_text;
+ }
+
+
+ /**
+ * Save paragraph by JS call
+ *
+ * @param
+ * @return
+ */
+ public function saveJS()
+ {
+ $ilCtrl = $this->ctrl;
+
+ $this->log->debug("start");
+
+ $this->updated = $this->content_obj->saveJS(
+ $this->pg_obj,
+ $_POST["ajaxform_content"],
+ ilUtil::stripSlashes($_POST["ajaxform_char"]),
+ ilUtil::stripSlashes($_POST["pc_id_str"])
+ );
+
+ $this->log->debug("ilPCParagraphGUI, saveJS: got updated value " . $this->updated);
+
+ if ($_POST["quick_save"]) {
+ if ($this->updated === true) {
+ $a_pc_id_str = $this->content_obj->getLastSavedPcId($this->pg_obj, true);
+ $this->log->debug("ilPCParagraphGUI, saveJS: echoing pc_id_str " . $a_pc_id_str . " (and exit)");
+ echo $a_pc_id_str;
+ exit;
+ }
+ }
+
+ if ($this->updated !== true && is_array($this->updated)) {
+ $this->outputError($this->updated);
+ }
+
+ $a_pc_id_str = $this->content_obj->getLastSavedPcId($this->pg_obj, true);
+
+ $ilCtrl->setParameterByClass(
+ $ilCtrl->getReturnClass($this),
+ "updated_pc_id_str",
+ urlencode($a_pc_id_str)
+ );
+ $this->log->debug("ilPCParagraphGUI, saveJS: redirecting to edit command of " . $ilCtrl->getReturnClass($this) . ".");
+ $ilCtrl->redirectByClass($ilCtrl->getReturnClass($this), "edit", "", true);
+ }
+
+ /**
+ * Output error
+ *
+ * @param array $a_err error array
+ */
+ public function outputError($a_err)
+ {
+ $err_str = "";
+ foreach ($a_err as $err) {
+ $err_str.= $err[1] . "";
-
- for ($j=0; $j < $rownums; $j++)
- {
- $indentno = strlen($rownums) - strlen($j+1) + 2;
- $rownumeration = ($j+1);
- $linenumbers .= "$rownumeration";
- if ($j < $rownums-1)
- {
- $linenumbers .= "\n";
- }
- }
- $linenumbers .= "
";
- $linenumbers .= "".$content."
";
+
+ for ($j=0; $j < $rownums; $j++) {
+ $indentno = strlen($rownums) - strlen($j+1) + 2;
+ $rownumeration = ($j+1);
+ $linenumbers .= "$rownumeration";
+ if ($j < $rownums-1) {
+ $linenumbers .= "\n";
+ }
+ }
+ $linenumbers .= "
";
+ $linenumbers .= "" . $content . "
'. - $char.' |
'. - $option.' |
'. - $option.' |
' . + $char . ' |
' . + $option . ' |
' . + $option . ' |
{$otitle} | @@ -499,154 +543,156 @@ CONTROL;|||
{$multi} |
".htmlentities($writer->xmlDumpMem(true)).""; exit; -//} - return $writer->xmlDumpMem(false); - } - - - /** - * Add records xml - * - * @param - * @return - */ - function addRecordsXml($a_writer, $a_prefixes, $a_entity, $a_schema_version, $a_ids, $a_field = "") - { - $types = $this->getXmlTypes($a_entity, $a_schema_version); + $this->ds_log->debug("Start writing Dataset, entity: " . $a_entity . ", schema version: " . $a_schema_version . + ", ids: " . print_r($a_ids, true)); + $writer->xmlStartTag($this->getDSPrefixString() . 'DataSet', $atts); + + // add types + if (!$a_omit_types) { + $this->ds_log->debug("...write types"); + $this->addTypesXml($writer, $a_entity, $a_schema_version); + } + + // add records + $this->ds_log->debug("...write records"); + $this->addRecordsXml($writer, $prefixes, $a_entity, $a_schema_version, $a_ids, $a_field); + + + $writer->xmlEndTag($this->getDSPrefixString() . "DataSet"); + //if ($a_entity == "mep") + //{ + // echo "
".htmlentities($writer->xmlDumpMem(true)).""; exit; + //} + return $writer->xmlDumpMem(false); + } + + + /** + * Add records xml + * + * @param + * @return + */ + public function addRecordsXml($a_writer, $a_prefixes, $a_entity, $a_schema_version, $a_ids, $a_field = "") + { + $types = $this->getXmlTypes($a_entity, $a_schema_version); - $this->ds_log->debug("...read data"); - $this->readData($a_entity, $a_schema_version, $a_ids, $a_field); - $this->ds_log->debug("...data: ".print_r($this->data, true)); - if (is_array($this->data)) - { - foreach ($this->data as $d) - { - $a_writer->xmlStartTag($this->getDSPrefixString()."Rec", - array("Entity" => $this->getXmlEntityName($a_entity, $a_schema_version))); + $this->ds_log->debug("...read data"); + $this->readData($a_entity, $a_schema_version, $a_ids, $a_field); + $this->ds_log->debug("...data: " . print_r($this->data, true)); + if (is_array($this->data)) { + foreach ($this->data as $d) { + $a_writer->xmlStartTag( + $this->getDSPrefixString() . "Rec", + array("Entity" => $this->getXmlEntityName($a_entity, $a_schema_version)) + ); - // entity tag - $a_writer->xmlStartTag($this->getXmlEntityTag($a_entity, $a_schema_version)); + // entity tag + $a_writer->xmlStartTag($this->getXmlEntityTag($a_entity, $a_schema_version)); - $rec = $this->getXmlRecord($a_entity, $a_schema_version, $d); - foreach ($rec as $f => $c) - { - switch ($types[$f]) - { - case "directory": - if ($this->absolute_export_dir != "" && $this->relative_export_dir != "") - { - ilUtil::makeDirParents($this->absolute_export_dir."/dsDir_".$this->dircnt); - ilUtil::rCopy($c, $this->absolute_export_dir."/dsDir_".$this->dircnt); -//echo "
ilExportOptions::EXPORT_BUILD
- * @param int ref_id of source
- * @return
- */
- public function getSubitemsForCreation($a_source_id)
- {
- $refs = array();
+ return $exp_id;
+ }
+
+ /**
+ * Get all subitems with mode ilExportOptions::EXPORT_BUILD
+ * @param int ref_id of source
+ * @return
+ */
+ public function getSubitemsForCreation($a_source_id)
+ {
+ $refs = array();
- foreach((array) $this->ref_options[self::KEY_ITEM_MODE] as $ref_id => $mode)
- {
- if($mode == self::EXPORT_BUILD)
- {
- $refs[] = $ref_id;
- }
- }
- return $refs;
- }
-
- /**
- * Get all subitems with mode != self::EXPORT_OMIT
- * @return array ref ids
- */
- public function getSubitemsForExport()
- {
- $refs = array();
- foreach((array) $this->ref_options[self::KEY_ITEM_MODE] as $ref_id => $mode)
- {
- if($mode != self::EXPORT_OMIT)
- {
- $refs[] = $ref_id;
- }
- }
- return $refs;
- }
-
- /**
- * Get export id
- * @return
- */
- public function getExportId()
- {
- return $this->export_id;
- }
-
- public function addOption($a_keyword, $a_ref_id, $a_obj_id, $a_value)
- {
- global $DIC;
+ foreach ((array) $this->ref_options[self::KEY_ITEM_MODE] as $ref_id => $mode) {
+ if ($mode == self::EXPORT_BUILD) {
+ $refs[] = $ref_id;
+ }
+ }
+ return $refs;
+ }
+
+ /**
+ * Get all subitems with mode != self::EXPORT_OMIT
+ * @return array ref ids
+ */
+ public function getSubitemsForExport()
+ {
+ $refs = array();
+ foreach ((array) $this->ref_options[self::KEY_ITEM_MODE] as $ref_id => $mode) {
+ if ($mode != self::EXPORT_OMIT) {
+ $refs[] = $ref_id;
+ }
+ }
+ return $refs;
+ }
+
+ /**
+ * Get export id
+ * @return
+ */
+ public function getExportId()
+ {
+ return $this->export_id;
+ }
+
+ public function addOption($a_keyword, $a_ref_id, $a_obj_id, $a_value)
+ {
+ global $DIC;
- $ilDB = $DIC['ilDB'];
-
- $query = "SELECT MAX(pos) position FROM export_options";
- $res = $ilDB->query($query);
-
- $pos = 0;
- while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT))
- {
- $pos = $row->position;
- }
- $pos++;
-
- $query = 'INSERT INTO export_options (export_id,keyword,ref_id,obj_id,value,pos) '.
- 'VALUES( '.
- $ilDB->quote($this->getExportId(),'integer').', '.
- $ilDB->quote($a_keyword,'integer').', '.
- $ilDB->quote($a_ref_id,'integer').', '.
- $ilDB->quote($a_obj_id,'integer').', '.
- $ilDB->quote($a_value,'integer').', '.
- $ilDB->quote($pos,'integer').' '.
- ')';
- $ilDB->manipulate($query);
- }
+ $ilDB = $DIC['ilDB'];
+
+ $query = "SELECT MAX(pos) position FROM export_options";
+ $res = $ilDB->query($query);
+
+ $pos = 0;
+ while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) {
+ $pos = $row->position;
+ }
+ $pos++;
+
+ $query = 'INSERT INTO export_options (export_id,keyword,ref_id,obj_id,value,pos) ' .
+ 'VALUES( ' .
+ $ilDB->quote($this->getExportId(), 'integer') . ', ' .
+ $ilDB->quote($a_keyword, 'integer') . ', ' .
+ $ilDB->quote($a_ref_id, 'integer') . ', ' .
+ $ilDB->quote($a_obj_id, 'integer') . ', ' .
+ $ilDB->quote($a_value, 'integer') . ', ' .
+ $ilDB->quote($pos, 'integer') . ' ' .
+ ')';
+ $ilDB->manipulate($query);
+ }
- /**
- * Get option
- * @param object $a_keyword
- * @return
- */
- public function getOption($a_keyword)
- {
- return isset($this->options[$a_keyword]) ? $this->options[$a_keyword] : null;
- }
-
- /**
- * Get option by
- * @param object $a_obj_id
- * @param object $a_keyword
- * @return
- */
- public function getOptionByObjId($a_obj_id,$a_keyword)
- {
- return isset($this->obj_options[$a_keyword][$a_obj_id]) ? $this->obj_options[$a_keyword][$a_obj_id] : null;
- }
-
- /**
- * Get option by
- * @param object $a_obj_id
- * @param object $a_keyword
- * @return
- */
- public function getOptionByRefId($a_ref_id,$a_keyword)
- {
- return isset($this->ref_options[$a_keyword][$a_ref_id]) ? $this->ref_options[$a_keyword][$a_ref_id] : null;
- }
-
- /**
- * Delete by export id
- * @return
- */
- public function delete()
- {
- global $DIC;
+ /**
+ * Get option
+ * @param object $a_keyword
+ * @return
+ */
+ public function getOption($a_keyword)
+ {
+ return isset($this->options[$a_keyword]) ? $this->options[$a_keyword] : null;
+ }
+
+ /**
+ * Get option by
+ * @param object $a_obj_id
+ * @param object $a_keyword
+ * @return
+ */
+ public function getOptionByObjId($a_obj_id, $a_keyword)
+ {
+ return isset($this->obj_options[$a_keyword][$a_obj_id]) ? $this->obj_options[$a_keyword][$a_obj_id] : null;
+ }
+
+ /**
+ * Get option by
+ * @param object $a_obj_id
+ * @param object $a_keyword
+ * @return
+ */
+ public function getOptionByRefId($a_ref_id, $a_keyword)
+ {
+ return isset($this->ref_options[$a_keyword][$a_ref_id]) ? $this->ref_options[$a_keyword][$a_ref_id] : null;
+ }
+
+ /**
+ * Delete by export id
+ * @return
+ */
+ public function delete()
+ {
+ global $DIC;
- $ilDB = $DIC['ilDB'];
-
- $query = "DELETE FROM export_options ".
- "WHERE export_id = ".$ilDB->quote($this->getExportId(),'integer');
- $ilDB->manipulate($query);
- return true;
- }
+ $ilDB = $DIC['ilDB'];
+
+ $query = "DELETE FROM export_options " .
+ "WHERE export_id = " . $ilDB->quote($this->getExportId(), 'integer');
+ $ilDB->manipulate($query);
+ return true;
+ }
- /**
- * Read entries
- * @return
- */
- public function read()
- {
- global $DIC;
+ /**
+ * Read entries
+ * @return
+ */
+ public function read()
+ {
+ global $DIC;
- $ilDB = $DIC['ilDB'];
-
- $this->options = array();
- $this->obj_options = array();
- $this->ref_options = array();
-
- $query = "SELECT * FROM export_options ".
- "WHERE export_id = ".$ilDB->quote($this->getExportId(),'integer').' '.
- "ORDER BY pos";
- $res = $ilDB->query($query);
- while($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT))
- {
- if($row->ref_id)
- {
- $this->ref_options[$row->keyword][$row->ref_id] = $row->value;
- }
- if($row->obj_id)
- {
- $this->obj_options[$row->keyword][$row->obj_id] = $row->value;
- }
- if(!$row->ref_id and !$row->obj_id)
- {
- $this->options[$row->keyword] = $row->value;
- }
-
- }
- return true;
- }
+ $ilDB = $DIC['ilDB'];
+
+ $this->options = array();
+ $this->obj_options = array();
+ $this->ref_options = array();
+
+ $query = "SELECT * FROM export_options " .
+ "WHERE export_id = " . $ilDB->quote($this->getExportId(), 'integer') . ' ' .
+ "ORDER BY pos";
+ $res = $ilDB->query($query);
+ while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) {
+ if ($row->ref_id) {
+ $this->ref_options[$row->keyword][$row->ref_id] = $row->value;
+ }
+ if ($row->obj_id) {
+ $this->obj_options[$row->keyword][$row->obj_id] = $row->value;
+ }
+ if (!$row->ref_id and !$row->obj_id) {
+ $this->options[$row->keyword] = $row->value;
+ }
+ }
+ return true;
+ }
}
-?>
\ No newline at end of file
diff --git a/Services/Export/classes/class.ilExportSelectionTableGUI.php b/Services/Export/classes/class.ilExportSelectionTableGUI.php
index bab746d7bc68e6f925293938101ce1dbe4e1b5ca..6dac61707662c6a5cba13297ca53ca96382976e5 100644
--- a/Services/Export/classes/class.ilExportSelectionTableGUI.php
+++ b/Services/Export/classes/class.ilExportSelectionTableGUI.php
@@ -17,202 +17,177 @@ include_once './Services/Export/classes/class.ilExportFileInfo.php';
class ilExportSelectionTableGUI extends ilTable2GUI
{
- /**
- *
- * @param object $a_parent_class
- * @param string $a_parent_cmd
- * @return
- */
- public function __construct($a_parent_class,$a_parent_cmd)
- {
- global $DIC;
+ /**
+ *
+ * @param object $a_parent_class
+ * @param string $a_parent_cmd
+ * @return
+ */
+ public function __construct($a_parent_class, $a_parent_cmd)
+ {
+ global $DIC;
- $lng = $DIC['lng'];
- $ilCtrl = $DIC['ilCtrl'];
- $ilUser = $DIC['ilUser'];
- $objDefinition = $DIC['objDefinition'];
-
- parent::__construct($a_parent_class,$a_parent_cmd);
-
- $this->lng = $lng;
- $this->lng->loadLanguageModule('export');
- $this->ctrl = $ilCtrl;
-
- $this->setTitle($this->lng->txt('export_select_resources'));
-
-
- $this->addColumn($this->lng->txt('title'),'');
- $this->addColumn($this->lng->txt('export_last_export'),'');
- $this->addColumn($this->lng->txt('export_last_export_file'),'');
- $this->addColumn($this->lng->txt('export_create_new_file'),'');
- $this->addColumn($this->lng->txt('export_omit_resource'),'');
-
- $this->setEnableHeader(true);
- $this->setFormAction($ilCtrl->getFormAction($this->getParentObject()));
- $this->setRowTemplate("tpl.export_item_selection_row.html", "Services/Export");
- $this->setEnableTitle(true);
- $this->setEnableNumInfo(true);
- $this->setLimit(10000);
-
- $this->setFormName('cmd');
-
- $this->addCommandButton('saveItemSelection', $this->lng->txt('export_save_selection'));
- $this->addCommandButton($a_parent_cmd, $this->lng->txt('cancel'));
- }
-
- public function fillRow($s)
- {
- if($s['last'])
- {
- $this->tpl->setCurrentBlock('footer_export_e');
- $this->tpl->setVariable('TXT_EXPORT_E_ALL',$this->lng->txt('select_all'));
- $this->tpl->parseCurrentBlock();
- $this->tpl->setCurrentBlock('footer_export');
- $this->tpl->setVariable('TXT_EXPORT_ALL',$this->lng->txt('select_all'));
- $this->tpl->parseCurrentBlock();
- $this->tpl->setCurrentBlock('footer_omit');
- $this->tpl->setVariable('TXT_OMIT_ALL',$this->lng->txt('select_all'));
- $this->tpl->parseCurrentBlock();
- return true;
- }
-
- for($i = 0; $i < $s['depth']; $i++)
- {
- $this->tpl->touchBlock('padding');
- $this->tpl->touchBlock('end_padding');
- }
- $this->tpl->setVariable('TREE_IMG',ilObject::_getIcon(ilObject::_lookupObjId($s['ref_id']), "tiny", $s['type']));
- $this->tpl->setVariable('TREE_ALT_IMG',$this->lng->txt('obj_'.$s['type']));
- $this->tpl->setVariable('TREE_TITLE',$s['title']);
-
-
- if($s['last_export'])
- {
- $this->tpl->setVariable('VAL_LAST_EXPORT',ilDatePresentation::formatDate(new ilDateTime($s['last_export'],IL_CAL_UNIX)));
- }
- else
- {
- $this->tpl->setVariable('VAL_LAST_EXPORT',$this->lng->txt('no_file'));
- }
+ $lng = $DIC['lng'];
+ $ilCtrl = $DIC['ilCtrl'];
+ $ilUser = $DIC['ilUser'];
+ $objDefinition = $DIC['objDefinition'];
+
+ parent::__construct($a_parent_class, $a_parent_cmd);
+
+ $this->lng = $lng;
+ $this->lng->loadLanguageModule('export');
+ $this->ctrl = $ilCtrl;
+
+ $this->setTitle($this->lng->txt('export_select_resources'));
+
+
+ $this->addColumn($this->lng->txt('title'), '');
+ $this->addColumn($this->lng->txt('export_last_export'), '');
+ $this->addColumn($this->lng->txt('export_last_export_file'), '');
+ $this->addColumn($this->lng->txt('export_create_new_file'), '');
+ $this->addColumn($this->lng->txt('export_omit_resource'), '');
+
+ $this->setEnableHeader(true);
+ $this->setFormAction($ilCtrl->getFormAction($this->getParentObject()));
+ $this->setRowTemplate("tpl.export_item_selection_row.html", "Services/Export");
+ $this->setEnableTitle(true);
+ $this->setEnableNumInfo(true);
+ $this->setLimit(10000);
+
+ $this->setFormName('cmd');
+
+ $this->addCommandButton('saveItemSelection', $this->lng->txt('export_save_selection'));
+ $this->addCommandButton($a_parent_cmd, $this->lng->txt('cancel'));
+ }
+
+ public function fillRow($s)
+ {
+ if ($s['last']) {
+ $this->tpl->setCurrentBlock('footer_export_e');
+ $this->tpl->setVariable('TXT_EXPORT_E_ALL', $this->lng->txt('select_all'));
+ $this->tpl->parseCurrentBlock();
+ $this->tpl->setCurrentBlock('footer_export');
+ $this->tpl->setVariable('TXT_EXPORT_ALL', $this->lng->txt('select_all'));
+ $this->tpl->parseCurrentBlock();
+ $this->tpl->setCurrentBlock('footer_omit');
+ $this->tpl->setVariable('TXT_OMIT_ALL', $this->lng->txt('select_all'));
+ $this->tpl->parseCurrentBlock();
+ return true;
+ }
+
+ for ($i = 0; $i < $s['depth']; $i++) {
+ $this->tpl->touchBlock('padding');
+ $this->tpl->touchBlock('end_padding');
+ }
+ $this->tpl->setVariable('TREE_IMG', ilObject::_getIcon(ilObject::_lookupObjId($s['ref_id']), "tiny", $s['type']));
+ $this->tpl->setVariable('TREE_ALT_IMG', $this->lng->txt('obj_' . $s['type']));
+ $this->tpl->setVariable('TREE_TITLE', $s['title']);
+
+
+ if ($s['last_export']) {
+ $this->tpl->setVariable('VAL_LAST_EXPORT', ilDatePresentation::formatDate(new ilDateTime($s['last_export'], IL_CAL_UNIX)));
+ } else {
+ $this->tpl->setVariable('VAL_LAST_EXPORT', $this->lng->txt('no_file'));
+ }
- if($s['source'])
- {
- return true;
- }
+ if ($s['source']) {
+ return true;
+ }
- // Export existing
- if($s['perm_export'] and $s['last_export'])
- {
- $this->tpl->setCurrentBlock('radio_export_e');
- $this->tpl->setVariable('TXT_EXPORT_E',$this->lng->txt('export_existing'));
- $this->tpl->setVariable('NAME_EXPORT_E','cp_options['.$s['ref_id'].'][type]');
- $this->tpl->setVariable('VALUE_EXPORT_E',ilExportOptions::EXPORT_EXISTING);
- $this->tpl->setVariable('ID_EXPORT_E',$s['depth'].'_'.$s['type'].'_'.$s['ref_id'].'_export_e');
- $this->tpl->setVariable('EXPORT_E_CHECKED','checked="checked"');
- $this->tpl->parseCurrentBlock();
- }
- elseif(!$s['perm_export'])
- {
- $this->tpl->setCurrentBlock('missing_export_perm');
- $this->tpl->setVariable('TXT_MISSING_EXPORT_PERM',$this->lng->txt('missing_perm'));
- $this->tpl->parseCurrentBlock();
- }
+ // Export existing
+ if ($s['perm_export'] and $s['last_export']) {
+ $this->tpl->setCurrentBlock('radio_export_e');
+ $this->tpl->setVariable('TXT_EXPORT_E', $this->lng->txt('export_existing'));
+ $this->tpl->setVariable('NAME_EXPORT_E', 'cp_options[' . $s['ref_id'] . '][type]');
+ $this->tpl->setVariable('VALUE_EXPORT_E', ilExportOptions::EXPORT_EXISTING);
+ $this->tpl->setVariable('ID_EXPORT_E', $s['depth'] . '_' . $s['type'] . '_' . $s['ref_id'] . '_export_e');
+ $this->tpl->setVariable('EXPORT_E_CHECKED', 'checked="checked"');
+ $this->tpl->parseCurrentBlock();
+ } elseif (!$s['perm_export']) {
+ $this->tpl->setCurrentBlock('missing_export_perm');
+ $this->tpl->setVariable('TXT_MISSING_EXPORT_PERM', $this->lng->txt('missing_perm'));
+ $this->tpl->parseCurrentBlock();
+ }
-
- // Create new
- if($s['perm_export'] and $s['export'])
- {
- $this->tpl->setCurrentBlock('radio_export');
- $this->tpl->setVariable('TXT_EXPORT',$this->lng->txt('export'));
- $this->tpl->setVariable('NAME_EXPORT','cp_options['.$s['ref_id'].'][type]');
- $this->tpl->setVariable('VALUE_EXPORT',ilExportOptions::EXPORT_BUILD);
- $this->tpl->setVariable('ID_EXPORT',$s['depth'].'_'.$s['type'].'_'.$s['ref_id'].'_export');
- if(!$copy or !$perm_copy)
- {
- $this->tpl->setVariable('EXPORT_CHECKED','checked="checked"');
- }
- $this->tpl->parseCurrentBlock();
- }
- elseif($s['export'])
- {
- $this->tpl->setCurrentBlock('missing_export_perm');
- $this->tpl->setVariable('TXT_MISSING_EXPORT_PERM',$this->lng->txt('missing_perm'));
- $this->tpl->parseCurrentBlock();
- }
-
- // Omit
- $this->tpl->setCurrentBlock('omit_radio');
- $this->tpl->setVariable('TXT_OMIT',$this->lng->txt('omit'));
- $this->tpl->setVariable('NAME_OMIT','cp_options['.$s['ref_id'].'][type]');
- $this->tpl->setVariable('VALUE_OMIT',ilExportOptions::EXPORT_OMIT);
- $this->tpl->setVariable('ID_OMIT',$s['depth'].'_'.$s['type'].'_'.$s['ref_id'].'_omit');
- if((!$s['copy'] or !$s['perm_copy']) and (!$s['link']))
- {
- $this->tpl->setVariable('OMIT_CHECKED','checked="checked"');
- }
- $this->tpl->parseCurrentBlock();
-
-
- }
-
- /**
- * parse tree
- * @param object $a_source
- * @return
- */
- public function parseContainer($a_source)
- {
- global $DIC;
+
+ // Create new
+ if ($s['perm_export'] and $s['export']) {
+ $this->tpl->setCurrentBlock('radio_export');
+ $this->tpl->setVariable('TXT_EXPORT', $this->lng->txt('export'));
+ $this->tpl->setVariable('NAME_EXPORT', 'cp_options[' . $s['ref_id'] . '][type]');
+ $this->tpl->setVariable('VALUE_EXPORT', ilExportOptions::EXPORT_BUILD);
+ $this->tpl->setVariable('ID_EXPORT', $s['depth'] . '_' . $s['type'] . '_' . $s['ref_id'] . '_export');
+ if (!$copy or !$perm_copy) {
+ $this->tpl->setVariable('EXPORT_CHECKED', 'checked="checked"');
+ }
+ $this->tpl->parseCurrentBlock();
+ } elseif ($s['export']) {
+ $this->tpl->setCurrentBlock('missing_export_perm');
+ $this->tpl->setVariable('TXT_MISSING_EXPORT_PERM', $this->lng->txt('missing_perm'));
+ $this->tpl->parseCurrentBlock();
+ }
+
+ // Omit
+ $this->tpl->setCurrentBlock('omit_radio');
+ $this->tpl->setVariable('TXT_OMIT', $this->lng->txt('omit'));
+ $this->tpl->setVariable('NAME_OMIT', 'cp_options[' . $s['ref_id'] . '][type]');
+ $this->tpl->setVariable('VALUE_OMIT', ilExportOptions::EXPORT_OMIT);
+ $this->tpl->setVariable('ID_OMIT', $s['depth'] . '_' . $s['type'] . '_' . $s['ref_id'] . '_omit');
+ if ((!$s['copy'] or !$s['perm_copy']) and (!$s['link'])) {
+ $this->tpl->setVariable('OMIT_CHECKED', 'checked="checked"');
+ }
+ $this->tpl->parseCurrentBlock();
+ }
+
+ /**
+ * parse tree
+ * @param object $a_source
+ * @return
+ */
+ public function parseContainer($a_source)
+ {
+ global $DIC;
- $tree = $DIC['tree'];
- $objDefinition = $DIC['objDefinition'];
- $ilAccess = $DIC['ilAccess'];
-
- $first = true;
- foreach($tree->getSubTree($root = $tree->getNodeData($a_source)) as $node)
- {
- if($node['type'] == 'rolf')
- {
- continue;
- }
- if(!$objDefinition->allowExport($node['type']))
- {
- #continue;
- }
- include_once("./Modules/File/classes/class.ilObjFileAccess.php");
- if ($node['type'] == "file" &&
- ilObjFileAccess::_isFileHidden($node['title']))
- {
- continue;
- }
- $r = array();
+ $tree = $DIC['tree'];
+ $objDefinition = $DIC['objDefinition'];
+ $ilAccess = $DIC['ilAccess'];
+
+ $first = true;
+ foreach ($tree->getSubTree($root = $tree->getNodeData($a_source)) as $node) {
+ if ($node['type'] == 'rolf') {
+ continue;
+ }
+ if (!$objDefinition->allowExport($node['type'])) {
+ #continue;
+ }
+ include_once("./Modules/File/classes/class.ilObjFileAccess.php");
+ if ($node['type'] == "file" &&
+ ilObjFileAccess::_isFileHidden($node['title'])) {
+ continue;
+ }
+ $r = array();
- if($last = ilExportFileInfo::lookupLastExport($node['obj_id'], 'xml'))
- {
- $r['last_export'] = $last->getCreationDate()->get(IL_CAL_UNIX);
- }
- else
- {
- $r['last_export'] = 0;
- }
-
- $r['last'] = false;
- $r['source']= $first;
- $r['ref_id']= $node['child'];
- $r['depth'] = $node['depth'] - $root['depth'];
- $r['type'] = $node['type'];
- $r['title'] = $node['title'];
- $r['export'] = $objDefinition->allowExport($node['type']);
- $r['perm_export'] = $ilAccess->checkAccess('write','',$node['child']);
+ if ($last = ilExportFileInfo::lookupLastExport($node['obj_id'], 'xml')) {
+ $r['last_export'] = $last->getCreationDate()->get(IL_CAL_UNIX);
+ } else {
+ $r['last_export'] = 0;
+ }
+
+ $r['last'] = false;
+ $r['source']= $first;
+ $r['ref_id']= $node['child'];
+ $r['depth'] = $node['depth'] - $root['depth'];
+ $r['type'] = $node['type'];
+ $r['title'] = $node['title'];
+ $r['export'] = $objDefinition->allowExport($node['type']);
+ $r['perm_export'] = $ilAccess->checkAccess('write', '', $node['child']);
- $rows[] = $r;
-
- $first = false;
- }
-
- $rows[] = array('last' => true);
- $this->setData((array) $rows);
- }
-
+ $rows[] = $r;
+
+ $first = false;
+ }
+
+ $rows[] = array('last' => true);
+ $this->setData((array) $rows);
+ }
}
-?>
\ No newline at end of file
diff --git a/Services/Export/classes/class.ilExportTableGUI.php b/Services/Export/classes/class.ilExportTableGUI.php
index 1f7da499117a02fe9f7b70dcfb4dc0a6ae5a358a..552a415356febc1bd94c980760e9b3087732ed05 100644
--- a/Services/Export/classes/class.ilExportTableGUI.php
+++ b/Services/Export/classes/class.ilExportTableGUI.php
@@ -1,4 +1,4 @@
-obj = $a_exp_obj;
-
- parent::__construct($a_parent_obj, $a_parent_cmd);
- $this->setData($this->getExportFiles());
- $this->setTitle($lng->txt('exp_export_files'));
-
- $this->initColumns();
-
- $this->setDefaultOrderField('timestamp');
- $this->setDefaultOrderDirection('desc');
-
- $this->setEnableHeader(true);
- $this->setFormAction($ilCtrl->getFormAction($a_parent_obj));
- $this->setRowTemplate('tpl.export_table_row.html', 'Services/Export');
- //$this->disable('footer');
- //$this->setEnableTitle(true);
+ $ilCtrl = $DIC['ilCtrl'];
+ $lng = $DIC['lng'];
+ $ilAccess = $DIC['ilAccess'];
+ $lng = $DIC['lng'];
+
+ $this->obj = $a_exp_obj;
+
+ parent::__construct($a_parent_obj, $a_parent_cmd);
+ $this->setData($this->getExportFiles());
+ $this->setTitle($lng->txt('exp_export_files'));
+
+ $this->initColumns();
+
+ $this->setDefaultOrderField('timestamp');
+ $this->setDefaultOrderDirection('desc');
+
+ $this->setEnableHeader(true);
+ $this->setFormAction($ilCtrl->getFormAction($a_parent_obj));
+ $this->setRowTemplate('tpl.export_table_row.html', 'Services/Export');
+ //$this->disable('footer');
+ //$this->setEnableTitle(true);
- $this->initMultiCommands();
- }
+ $this->initMultiCommands();
+ }
- /**
- *
- */
- protected function initColumns()
- {
- $this->addColumn($this->lng->txt(''), '', '1', true);
- $this->addColumn($this->lng->txt('type'), 'type');
- $this->addColumn($this->lng->txt('file'), 'file');
- $this->addColumn($this->lng->txt('size'), 'size');
- $this->addColumn($this->lng->txt('date'), 'timestamp');
- }
-
- protected function prepareOutput()
- {
- // append at last position (after custom columns)
- $this->addColumn($this->lng->txt('actions'));
- }
+ /**
+ *
+ */
+ protected function initColumns()
+ {
+ $this->addColumn($this->lng->txt(''), '', '1', true);
+ $this->addColumn($this->lng->txt('type'), 'type');
+ $this->addColumn($this->lng->txt('file'), 'file');
+ $this->addColumn($this->lng->txt('size'), 'size');
+ $this->addColumn($this->lng->txt('date'), 'timestamp');
+ }
+
+ protected function prepareOutput()
+ {
+ // append at last position (after custom columns)
+ $this->addColumn($this->lng->txt('actions'));
+ }
- /**
- *
- */
- protected function initMultiCommands()
- {
- // $this->addMultiCommand('download', $this->lng->txt('download')); #15097
- $this->addMultiCommand('confirmDeletion', $this->lng->txt('delete'));
- }
+ /**
+ *
+ */
+ protected function initMultiCommands()
+ {
+ // $this->addMultiCommand('download', $this->lng->txt('download')); #15097
+ $this->addMultiCommand('confirmDeletion', $this->lng->txt('delete'));
+ }
- /**
- * Add custom column
- *
- * @param
- * @return
- */
- function addCustomColumn($a_txt, $a_obj, $a_func)
- {
- $this->addColumn($a_txt);
- $this->custom_columns[] = array('txt' => $a_txt,
- 'obj' => $a_obj,
- 'func' => $a_func);
- }
-
- /**
- * Add custom multi command
- *
- * @param
- * @return
- */
- function addCustomMultiCommand($a_txt, $a_cmd)
- {
- $this->addMultiCommand($a_cmd, $a_txt);
- }
+ /**
+ * Add custom column
+ *
+ * @param
+ * @return
+ */
+ public function addCustomColumn($a_txt, $a_obj, $a_func)
+ {
+ $this->addColumn($a_txt);
+ $this->custom_columns[] = array('txt' => $a_txt,
+ 'obj' => $a_obj,
+ 'func' => $a_func);
+ }
+
+ /**
+ * Add custom multi command
+ *
+ * @param
+ * @return
+ */
+ public function addCustomMultiCommand($a_txt, $a_cmd)
+ {
+ $this->addMultiCommand($a_cmd, $a_txt);
+ }
- /**
- * Get custom columns
- *
- * @param
- * @return
- */
- function getCustomColumns()
- {
- return $this->custom_columns;
- }
-
- /**
- * Get export files
- */
- function getExportFiles()
- {
- $types = array();
- foreach ($this->parent_obj->getFormats() as $f)
- {
- $types[] = $f['key'];
- $this->formats[$f['key']] = $f['txt'];
- }
- include_once('./Services/Export/classes/class.ilExport.php');
- $files = ilExport::_getExportFiles($this->obj->getId(),
- $types, $this->obj->getType());
- return $files;
- }
+ /**
+ * Get custom columns
+ *
+ * @param
+ * @return
+ */
+ public function getCustomColumns()
+ {
+ return $this->custom_columns;
+ }
+
+ /**
+ * Get export files
+ */
+ public function getExportFiles()
+ {
+ $types = array();
+ foreach ($this->parent_obj->getFormats() as $f) {
+ $types[] = $f['key'];
+ $this->formats[$f['key']] = $f['txt'];
+ }
+ include_once('./Services/Export/classes/class.ilExport.php');
+ $files = ilExport::_getExportFiles(
+ $this->obj->getId(),
+ $types,
+ $this->obj->getType()
+ );
+ return $files;
+ }
- /**
- * @param array $a_set
- */
- protected function fillRow($a_set)
- {
- global $DIC;
+ /**
+ * @param array $a_set
+ */
+ protected function fillRow($a_set)
+ {
+ global $DIC;
- $ilCtrl = $DIC['ilCtrl'];
-
- foreach($this->getCustomColumns() as $c)
- {
- $this->tpl->setCurrentBlock('custom');
- $f = $c['func'];
- $this->tpl->setVariable('VAL_CUSTOM', $c['obj']->$f($a_set['type'], $a_set['file']).' ');
- $this->tpl->parseCurrentBlock();
- }
-
- $file_id = $this->getRowId($a_set);
- $this->tpl->setVariable('VAL_ID', $file_id);
+ $ilCtrl = $DIC['ilCtrl'];
+
+ foreach ($this->getCustomColumns() as $c) {
+ $this->tpl->setCurrentBlock('custom');
+ $f = $c['func'];
+ $this->tpl->setVariable('VAL_CUSTOM', $c['obj']->$f($a_set['type'], $a_set['file']) . ' ');
+ $this->tpl->parseCurrentBlock();
+ }
+
+ $file_id = $this->getRowId($a_set);
+ $this->tpl->setVariable('VAL_ID', $file_id);
- $type = ($this->formats[$a_set['type']] != "")
- ? $this->formats[$a_set['type']]
- : $a_set['type'];
- $this->tpl->setVariable('VAL_TYPE', $type);
- $this->tpl->setVariable('VAL_FILE', $a_set['file']);
- $this->tpl->setVariable('VAL_SIZE', ilUtil::formatSize($a_set['size']));
- $this->tpl->setVariable('VAL_DATE', ilDatePresentation::formatDate(new ilDateTime($a_set['timestamp'], IL_CAL_UNIX)));
-
- $this->tpl->setVariable('TXT_DOWNLOAD', $this->lng->txt('download'));
-
- $ilCtrl->setParameter($this->getParentObject(), "file", $file_id);
- $url = $ilCtrl->getLinkTarget($this->getParentObject(), "download");
- $ilCtrl->setParameter($this->getParentObject(), "file", "");
- $this->tpl->setVariable('URL_DOWNLOAD', $url);
- }
+ $type = ($this->formats[$a_set['type']] != "")
+ ? $this->formats[$a_set['type']]
+ : $a_set['type'];
+ $this->tpl->setVariable('VAL_TYPE', $type);
+ $this->tpl->setVariable('VAL_FILE', $a_set['file']);
+ $this->tpl->setVariable('VAL_SIZE', ilUtil::formatSize($a_set['size']));
+ $this->tpl->setVariable('VAL_DATE', ilDatePresentation::formatDate(new ilDateTime($a_set['timestamp'], IL_CAL_UNIX)));
+
+ $this->tpl->setVariable('TXT_DOWNLOAD', $this->lng->txt('download'));
+
+ $ilCtrl->setParameter($this->getParentObject(), "file", $file_id);
+ $url = $ilCtrl->getLinkTarget($this->getParentObject(), "download");
+ $ilCtrl->setParameter($this->getParentObject(), "file", "");
+ $this->tpl->setVariable('URL_DOWNLOAD', $url);
+ }
- /**
- * @param array $row
- * @return string
- */
- protected function getRowId(array $row)
- {
- return $row['type'].':'.$row['file'];
- }
-}
\ No newline at end of file
+ /**
+ * @param array $row
+ * @return string
+ */
+ protected function getRowId(array $row)
+ {
+ return $row['type'] . ':' . $row['file'];
+ }
+}
diff --git a/Services/Export/classes/class.ilImport.php b/Services/Export/classes/class.ilImport.php
index cb888f2189f912b2c9ac8c37d8473c9b7ba6f3c8..44c7ab205ba2921fd4f07fec4771c7987bb86542 100644
--- a/Services/Export/classes/class.ilImport.php
+++ b/Services/Export/classes/class.ilImport.php
@@ -10,383 +10,369 @@
*/
class ilImport
{
- /**
- * @var ilLogger
- */
- protected $log;
-
- protected $install_id = "";
- protected $install_url = "";
- protected $entities = "";
- protected $tmp_import_dir = "";
-
- protected $mapping = null;
- protected $skip_entity = array();
- protected $configs = array();
-
- /**
- * Constructor
- *
- * @param int id of parent container
- * @return
- */
- function __construct($a_target_id = 0)
- {
- include_once("./Services/Export/classes/class.ilImportMapping.php");
- $this->mapping = new ilImportMapping();
- $this->mapping->setTargetId($a_target_id);
- $this->log = ilLoggerFactory::getLogger('exp');
- }
-
- /**
- * Get configuration (note that configurations are optional, null may be returned!)
- *
- * @param string $a_comp component (e.g. "Modules/Glossary")
- * @return ilImportConfig $a_comp configuration object or null
- * @throws ilImportException
- */
- function getConfig($a_comp)
- {
- // if created, return existing config object
- if (isset($this->configs[$a_comp]))
- {
- return $this->configs[$a_comp];
- }
-
- // create instance of export config object
- $comp_arr = explode("/", $a_comp);
- $a_class = "il".$comp_arr[1]."ImportConfig";
- $import_config_file = "./".$a_comp."/classes/class.".$a_class.".php";
- if (!is_file($import_config_file))
- {
- include_once("./Services/Export/exceptions/class.ilImportException.php");
- throw new ilImportException('Component "'.$a_comp.'" does not provide ImportConfig class.');
- }
- include_once($import_config_file);
- $imp_config = new $a_class();
- $this->configs[$a_comp] = $imp_config;
-
- return $imp_config;
- }
-
- /**
- * Get mapping object
- * @return ilImportMapping ilImportMapping
- */
- public function getMapping()
- {
- return $this->mapping;
- }
-
- /**
- * Set entity types
- *
- * @param array entity types
- */
- final function setEntityTypes($a_val)
- {
- $this->entity_types = $a_val;
- }
-
- /**
- * Get entity types
- *
- * @return array entity types
- */
- final function getEntityTypes()
- {
- return $this->entity_types;
- }
-
- /**
- * Add skip entity
- *
- * @param string $a_val component
- * @param string $a_val entity
- */
- function addSkipEntity($a_component, $a_entity, $skip = true)
- {
- $this->skip_entity[$a_component][$a_entity] = $skip;
- }
-
- /**
- * Set currrent dataset
- *
- * @param object currrent dataset
- */
- function setCurrentDataset($a_val)
- {
- $this->current_dataset = $a_val;
- }
-
- /**
- *
- * Get currrent dataset
- *
- * @return object currrent dataset
- */
- function getCurrentDataset()
- {
- return $this->current_dataset;
- }
-
- /**
- * After entity types are parsed
- */
- function afterEntityTypes()
- {
- $this->getCurrentDataset()->setImport($this);
- }
-
- /**
- * After entity types are parsed
- *
- * @param
- */
- function importRecord($a_entity, $a_types, $a_record)
- {
- $this->getCurrentDataset()->importRecord($a_entity, $a_types, $a_record);
- }
-
-
- /**
- * Import entity
- */
- final public function importEntity($a_tmp_file, $a_filename,
- $a_entity, $a_component, $a_copy_file = false)
- {
- $this->importObject(null, $a_tmp_file, $a_filename, $a_entity, $a_component, $a_copy_file);
- }
-
-
- /**
- * Import repository object export file
- *
- * @param string absolute filename of temporary upload file
- */
- final public function importObject($a_new_obj, $a_tmp_file, $a_filename, $a_type,
- $a_comp = "", $a_copy_file = false)
- {
-
- // create temporary directory
- $tmpdir = ilUtil::ilTempnam();
- ilUtil::makeDir($tmpdir);
- if ($a_copy_file)
- {
- copy($a_tmp_file, $tmpdir."/".$a_filename);
- }
- else
- {
- ilUtil::moveUploadedFile($a_tmp_file, $a_filename, $tmpdir."/".$a_filename);
- }
-
- $this->log->debug("unzip: ".$tmpdir."/".$a_filename);
-
- ilUtil::unzip($tmpdir."/".$a_filename);
- $dir = $tmpdir."/".substr($a_filename, 0, strlen($a_filename) - 4);
-
- $this->setTemporaryImportDir($dir);
-
- $this->log->debug("dir: ".$dir);
-
- $ret = $this->doImportObject($dir, $a_type, $a_comp, $tmpdir);
- $new_id = null;
- if(is_array($ret))
- {
- $new_id = $ret['new_id'];
- }
-
- // delete temporary directory
- ilUtil::delDir($tmpdir);
- return $new_id;
- }
-
- /**
- * Import from directory
- *
- * @param
- * @return
- */
- function importFromDirectory($dir, $a_type, $a_comp)
- {
- $ret = $this->doImportObject($dir, $a_type, $a_comp);
-
- if(is_array($ret))
- {
- return $ret['new_id'];
- }
- return null;
- }
-
-
- /**
- * Set temporary import directory
- *
- * @param string $a_val temporary import directory (used to unzip and read import)
- */
- protected function setTemporaryImportDir($a_val)
- {
- $this->tmp_import_dir = $a_val;
- }
-
- /**
- * Get temporary import directory
- *
- * @return string temporary import directory (used to unzip and read import)
- */
- public function getTemporaryImportDir()
- {
- return $this->tmp_import_dir;
- }
-
- /**
- * Import repository object export file
- *
- * @param string absolute filename of temporary upload file
- */
- protected function doImportObject($dir, $a_type, $a_component = "", $a_tmpdir = "")
- {
- if ($a_component == "")
- {
- include_once("./Services/Export/classes/class.ilImportExportFactory.php");
- $a_component = ilImportExportFactory::getComponentForExport($a_type);
- }
- $this->comp = $a_component;
-
- // get import class
- $success = true;
-
- // process manifest file
- include_once("./Services/Export/classes/class.ilManifestParser.php");
- if (!is_file($dir."/manifest.xml"))
- {
- include_once("./Services/Export/exceptions/class.ilManifestFileNotFoundImportException.php");
- $mess = (DEVMODE)
- ? 'Manifest file not found: "'.$dir."/manifest.xml".'".'
- : 'Manifest file not found: "manifest.xml."';
- $e = new ilManifestFileNotFoundImportException($mess);
- $e->setManifestDir($dir);
- $e->setTmpDir($a_tmpdir);
- throw $e;
- }
- $parser = new ilManifestParser($dir."/manifest.xml");
- $this->mapping->setInstallUrl($parser->getInstallUrl());
- $this->mapping->setInstallId($parser->getInstallId());
-
- // check for correct type
- if ($parser->getMainEntity() != $a_type)
- {
- include_once("./Services/Export/exceptions/class.ilImportObjectTypeMismatchException.php");
- $e = new ilImportObjectTypeMismatchException("Object type does not match. Import file has type '".$parser->getMainEntity()."' but import being processed for '".$a_type."'.");
- throw $e;
- }
-
- // process export files
- $expfiles = $parser->getExportFiles();
-
- include_once("./Services/Export/classes/class.ilExportFileParser.php");
- include_once("./Services/Export/classes/class.ilImportExportFactory.php");
- $all_importers = array();
- foreach ($expfiles as $expfile)
- {
- $comp = $expfile["component"];
- $class = ilImportExportFactory::getImporterClass($comp);
-
- // log a warning for inactive page component plugins, but continue import
- // page content will be imported, but not its additional data
- // (other plugins throw an exception in ilImportExportFactory)
- if ($class == '')
- {
- $this->log->warning("no class found for component: $comp");
- continue;
- }
-
- $this->log->debug("create new class = $class");
-
- $this->importer = new $class();
- $this->importer->setImport($this);
- $all_importers[] = $this->importer;
- $this->importer->setImportDirectory($dir);
- $this->importer->init();
- $this->current_comp = $comp;
- try {
- $this->log->debug("Process file: ".$dir."/".$expfile["path"]);
- $parser = new ilExportFileParser($dir."/".$expfile["path"],$this, "processItemXml");
- }
- catch(Exception $e)
- {
- $this->log->error("Import failed: ".$e->getMessage());
- throw $e;
- }
- }
-
- // write import ids before(!) final processing
- $obj_map = $this->getMapping()->getMappingsOfEntity('Services/Container', 'objs');
- if (is_array($obj_map))
- {
- foreach ($obj_map as $obj_id_old => $obj_id_new)
- {
- ilObject::_writeImportId($obj_id_new, "il_".$this->mapping->getInstallId()."_".ilObject::_lookupType($obj_id_new)."_".$obj_id_old);
- }
- }
-
- // final processing
- foreach ($all_importers as $imp)
- {
- $this->log->debug("Call finalProcessing for: ".get_class($imp));
- $imp->finalProcessing($this->mapping);
- }
-
- // we should only get on mapping here
- $top_mapping = $this->mapping->getMappingsOfEntity($this->comp, $a_type);
- $new_id = (int) current($top_mapping);
- return array(
- 'new_id' => $new_id,
- 'importers' => (array) $all_importers
- );
- }
-
- /**
- * Process item xml
- *
- * @global ilObjectDefinition $objDefinition
- */
- function processItemXml($a_entity, $a_schema_version, $a_id, $a_xml,$a_install_id, $a_install_url)
- {
- global $DIC;
-
- $objDefinition = $DIC['objDefinition'];
-
- // skip
- if ($this->skip_entity[$this->current_comp][$a_entity])
- {
- return;
- }
-
- if($objDefinition->isRBACObject($a_entity) &&
- $this->getMapping()->getMapping('Services/Container', 'imported', $a_id))
- {
- $this->log->info('Ignoring referenced '.$a_entity.' with id '.$a_id);
- return;
- }
- $this->importer->setInstallId($a_install_id);
- $this->importer->setInstallUrl($a_install_url);
- $this->importer->setSchemaVersion($a_schema_version);
- $this->importer->setSkipEntities($this->skip_entity);
- $new_id = $this->importer->importXmlRepresentation($a_entity, $a_id, $a_xml, $this->mapping);
-
- // Store information about imported obj_ids in mapping to avoid double imports of references
- if($objDefinition->isRBACObject($a_entity))
- {
- $this->getMapping()->addMapping('Services/Container', 'imported', $a_id, 1);
- }
-
- // @TODO new id is not always set
- if($new_id && $new_id !== true)
- {
- $this->mapping->addMapping($this->comp ,$a_entity, $a_id, $new_id);
- }
- }
-
+ /**
+ * @var ilLogger
+ */
+ protected $log;
+
+ protected $install_id = "";
+ protected $install_url = "";
+ protected $entities = "";
+ protected $tmp_import_dir = "";
+
+ protected $mapping = null;
+ protected $skip_entity = array();
+ protected $configs = array();
+
+ /**
+ * Constructor
+ *
+ * @param int id of parent container
+ * @return
+ */
+ public function __construct($a_target_id = 0)
+ {
+ include_once("./Services/Export/classes/class.ilImportMapping.php");
+ $this->mapping = new ilImportMapping();
+ $this->mapping->setTargetId($a_target_id);
+ $this->log = ilLoggerFactory::getLogger('exp');
+ }
+
+ /**
+ * Get configuration (note that configurations are optional, null may be returned!)
+ *
+ * @param string $a_comp component (e.g. "Modules/Glossary")
+ * @return ilImportConfig $a_comp configuration object or null
+ * @throws ilImportException
+ */
+ public function getConfig($a_comp)
+ {
+ // if created, return existing config object
+ if (isset($this->configs[$a_comp])) {
+ return $this->configs[$a_comp];
+ }
+
+ // create instance of export config object
+ $comp_arr = explode("/", $a_comp);
+ $a_class = "il" . $comp_arr[1] . "ImportConfig";
+ $import_config_file = "./" . $a_comp . "/classes/class." . $a_class . ".php";
+ if (!is_file($import_config_file)) {
+ include_once("./Services/Export/exceptions/class.ilImportException.php");
+ throw new ilImportException('Component "' . $a_comp . '" does not provide ImportConfig class.');
+ }
+ include_once($import_config_file);
+ $imp_config = new $a_class();
+ $this->configs[$a_comp] = $imp_config;
+
+ return $imp_config;
+ }
+
+ /**
+ * Get mapping object
+ * @return ilImportMapping ilImportMapping
+ */
+ public function getMapping()
+ {
+ return $this->mapping;
+ }
+
+ /**
+ * Set entity types
+ *
+ * @param array entity types
+ */
+ final public function setEntityTypes($a_val)
+ {
+ $this->entity_types = $a_val;
+ }
+
+ /**
+ * Get entity types
+ *
+ * @return array entity types
+ */
+ final public function getEntityTypes()
+ {
+ return $this->entity_types;
+ }
+
+ /**
+ * Add skip entity
+ *
+ * @param string $a_val component
+ * @param string $a_val entity
+ */
+ public function addSkipEntity($a_component, $a_entity, $skip = true)
+ {
+ $this->skip_entity[$a_component][$a_entity] = $skip;
+ }
+
+ /**
+ * Set currrent dataset
+ *
+ * @param object currrent dataset
+ */
+ public function setCurrentDataset($a_val)
+ {
+ $this->current_dataset = $a_val;
+ }
+
+ /**
+ *
+ * Get currrent dataset
+ *
+ * @return object currrent dataset
+ */
+ public function getCurrentDataset()
+ {
+ return $this->current_dataset;
+ }
+
+ /**
+ * After entity types are parsed
+ */
+ public function afterEntityTypes()
+ {
+ $this->getCurrentDataset()->setImport($this);
+ }
+
+ /**
+ * After entity types are parsed
+ *
+ * @param
+ */
+ public function importRecord($a_entity, $a_types, $a_record)
+ {
+ $this->getCurrentDataset()->importRecord($a_entity, $a_types, $a_record);
+ }
+
+
+ /**
+ * Import entity
+ */
+ final public function importEntity(
+ $a_tmp_file,
+ $a_filename,
+ $a_entity,
+ $a_component,
+ $a_copy_file = false
+ ) {
+ $this->importObject(null, $a_tmp_file, $a_filename, $a_entity, $a_component, $a_copy_file);
+ }
+
+
+ /**
+ * Import repository object export file
+ *
+ * @param string absolute filename of temporary upload file
+ */
+ final public function importObject(
+ $a_new_obj,
+ $a_tmp_file,
+ $a_filename,
+ $a_type,
+ $a_comp = "",
+ $a_copy_file = false
+ ) {
+
+ // create temporary directory
+ $tmpdir = ilUtil::ilTempnam();
+ ilUtil::makeDir($tmpdir);
+ if ($a_copy_file) {
+ copy($a_tmp_file, $tmpdir . "/" . $a_filename);
+ } else {
+ ilUtil::moveUploadedFile($a_tmp_file, $a_filename, $tmpdir . "/" . $a_filename);
+ }
+
+ $this->log->debug("unzip: " . $tmpdir . "/" . $a_filename);
+
+ ilUtil::unzip($tmpdir . "/" . $a_filename);
+ $dir = $tmpdir . "/" . substr($a_filename, 0, strlen($a_filename) - 4);
+
+ $this->setTemporaryImportDir($dir);
+
+ $this->log->debug("dir: " . $dir);
+
+ $ret = $this->doImportObject($dir, $a_type, $a_comp, $tmpdir);
+ $new_id = null;
+ if (is_array($ret)) {
+ $new_id = $ret['new_id'];
+ }
+
+ // delete temporary directory
+ ilUtil::delDir($tmpdir);
+ return $new_id;
+ }
+
+ /**
+ * Import from directory
+ *
+ * @param
+ * @return
+ */
+ public function importFromDirectory($dir, $a_type, $a_comp)
+ {
+ $ret = $this->doImportObject($dir, $a_type, $a_comp);
+
+ if (is_array($ret)) {
+ return $ret['new_id'];
+ }
+ return null;
+ }
+
+
+ /**
+ * Set temporary import directory
+ *
+ * @param string $a_val temporary import directory (used to unzip and read import)
+ */
+ protected function setTemporaryImportDir($a_val)
+ {
+ $this->tmp_import_dir = $a_val;
+ }
+
+ /**
+ * Get temporary import directory
+ *
+ * @return string temporary import directory (used to unzip and read import)
+ */
+ public function getTemporaryImportDir()
+ {
+ return $this->tmp_import_dir;
+ }
+
+ /**
+ * Import repository object export file
+ *
+ * @param string absolute filename of temporary upload file
+ */
+ protected function doImportObject($dir, $a_type, $a_component = "", $a_tmpdir = "")
+ {
+ if ($a_component == "") {
+ include_once("./Services/Export/classes/class.ilImportExportFactory.php");
+ $a_component = ilImportExportFactory::getComponentForExport($a_type);
+ }
+ $this->comp = $a_component;
+
+ // get import class
+ $success = true;
+
+ // process manifest file
+ include_once("./Services/Export/classes/class.ilManifestParser.php");
+ if (!is_file($dir . "/manifest.xml")) {
+ include_once("./Services/Export/exceptions/class.ilManifestFileNotFoundImportException.php");
+ $mess = (DEVMODE)
+ ? 'Manifest file not found: "' . $dir . "/manifest.xml" . '".'
+ : 'Manifest file not found: "manifest.xml."';
+ $e = new ilManifestFileNotFoundImportException($mess);
+ $e->setManifestDir($dir);
+ $e->setTmpDir($a_tmpdir);
+ throw $e;
+ }
+ $parser = new ilManifestParser($dir . "/manifest.xml");
+ $this->mapping->setInstallUrl($parser->getInstallUrl());
+ $this->mapping->setInstallId($parser->getInstallId());
+
+ // check for correct type
+ if ($parser->getMainEntity() != $a_type) {
+ include_once("./Services/Export/exceptions/class.ilImportObjectTypeMismatchException.php");
+ $e = new ilImportObjectTypeMismatchException("Object type does not match. Import file has type '" . $parser->getMainEntity() . "' but import being processed for '" . $a_type . "'.");
+ throw $e;
+ }
+
+ // process export files
+ $expfiles = $parser->getExportFiles();
+
+ include_once("./Services/Export/classes/class.ilExportFileParser.php");
+ include_once("./Services/Export/classes/class.ilImportExportFactory.php");
+ $all_importers = array();
+ foreach ($expfiles as $expfile) {
+ $comp = $expfile["component"];
+ $class = ilImportExportFactory::getImporterClass($comp);
+
+ // log a warning for inactive page component plugins, but continue import
+ // page content will be imported, but not its additional data
+ // (other plugins throw an exception in ilImportExportFactory)
+ if ($class == '') {
+ $this->log->warning("no class found for component: $comp");
+ continue;
+ }
+
+ $this->log->debug("create new class = $class");
+
+ $this->importer = new $class();
+ $this->importer->setImport($this);
+ $all_importers[] = $this->importer;
+ $this->importer->setImportDirectory($dir);
+ $this->importer->init();
+ $this->current_comp = $comp;
+ try {
+ $this->log->debug("Process file: " . $dir . "/" . $expfile["path"]);
+ $parser = new ilExportFileParser($dir . "/" . $expfile["path"], $this, "processItemXml");
+ } catch (Exception $e) {
+ $this->log->error("Import failed: " . $e->getMessage());
+ throw $e;
+ }
+ }
+
+ // write import ids before(!) final processing
+ $obj_map = $this->getMapping()->getMappingsOfEntity('Services/Container', 'objs');
+ if (is_array($obj_map)) {
+ foreach ($obj_map as $obj_id_old => $obj_id_new) {
+ ilObject::_writeImportId($obj_id_new, "il_" . $this->mapping->getInstallId() . "_" . ilObject::_lookupType($obj_id_new) . "_" . $obj_id_old);
+ }
+ }
+
+ // final processing
+ foreach ($all_importers as $imp) {
+ $this->log->debug("Call finalProcessing for: " . get_class($imp));
+ $imp->finalProcessing($this->mapping);
+ }
+
+ // we should only get on mapping here
+ $top_mapping = $this->mapping->getMappingsOfEntity($this->comp, $a_type);
+ $new_id = (int) current($top_mapping);
+ return array(
+ 'new_id' => $new_id,
+ 'importers' => (array) $all_importers
+ );
+ }
+
+ /**
+ * Process item xml
+ *
+ * @global ilObjectDefinition $objDefinition
+ */
+ public function processItemXml($a_entity, $a_schema_version, $a_id, $a_xml, $a_install_id, $a_install_url)
+ {
+ global $DIC;
+
+ $objDefinition = $DIC['objDefinition'];
+
+ // skip
+ if ($this->skip_entity[$this->current_comp][$a_entity]) {
+ return;
+ }
+
+ if ($objDefinition->isRBACObject($a_entity) &&
+ $this->getMapping()->getMapping('Services/Container', 'imported', $a_id)) {
+ $this->log->info('Ignoring referenced ' . $a_entity . ' with id ' . $a_id);
+ return;
+ }
+ $this->importer->setInstallId($a_install_id);
+ $this->importer->setInstallUrl($a_install_url);
+ $this->importer->setSchemaVersion($a_schema_version);
+ $this->importer->setSkipEntities($this->skip_entity);
+ $new_id = $this->importer->importXmlRepresentation($a_entity, $a_id, $a_xml, $this->mapping);
+
+ // Store information about imported obj_ids in mapping to avoid double imports of references
+ if ($objDefinition->isRBACObject($a_entity)) {
+ $this->getMapping()->addMapping('Services/Container', 'imported', $a_id, 1);
+ }
+
+ // @TODO new id is not always set
+ if ($new_id && $new_id !== true) {
+ $this->mapping->addMapping($this->comp, $a_entity, $a_id, $new_id);
+ }
+ }
}
-?>
\ No newline at end of file
diff --git a/Services/Export/classes/class.ilImportConfig.php b/Services/Export/classes/class.ilImportConfig.php
index 0ccacb7252a8e1b5fe555a694216733749767a8c..d35c1237ac103811d96096ffae303508f30b5ec7 100644
--- a/Services/Export/classes/class.ilImportConfig.php
+++ b/Services/Export/classes/class.ilImportConfig.php
@@ -11,8 +11,4 @@
*/
abstract class ilImportConfig
{
-
-
}
-
-?>
\ No newline at end of file
diff --git a/Services/Export/classes/class.ilImportContainer.php b/Services/Export/classes/class.ilImportContainer.php
index 136b0806a4382624a120ea48429d5828c2893023..009f4eb2a19dd5c7ca341aa184a65f5b6aa791ed 100644
--- a/Services/Export/classes/class.ilImportContainer.php
+++ b/Services/Export/classes/class.ilImportContainer.php
@@ -12,104 +12,97 @@ include_once './Services/Export/classes/class.ilImport.php';
*/
class ilImportContainer extends ilImport
{
- /**
- * Constructor
- * @param int $a_target_id Id of parent node
- * @return
- */
- public function __construct($a_target_id)
- {
- parent::__construct($a_target_id);
- }
+ /**
+ * Constructor
+ * @param int $a_target_id Id of parent node
+ * @return
+ */
+ public function __construct($a_target_id)
+ {
+ parent::__construct($a_target_id);
+ }
- /**
- * Import a container
- * @param object $dir
- * @param object $type
- * @return
- */
- protected function doImportObject($dir, $type, $a_component = "", $a_tmpdir = "")
- {
- $manifest_file = $dir."/manifest.xml";
- if(!file_exists($manifest_file))
- {
- return false;
- }
-
- include_once("./Services/Export/classes/class.ilManifestParser.php");
- $parser = new ilManifestParser($manifest_file);
-
-
- // begin-patch optes_lok_export
+ /**
+ * Import a container
+ * @param object $dir
+ * @param object $type
+ * @return
+ */
+ protected function doImportObject($dir, $type, $a_component = "", $a_tmpdir = "")
+ {
+ $manifest_file = $dir . "/manifest.xml";
+ if (!file_exists($manifest_file)) {
+ return false;
+ }
+
+ include_once("./Services/Export/classes/class.ilManifestParser.php");
+ $parser = new ilManifestParser($manifest_file);
+
+
+ // begin-patch optes_lok_export
- // Handling single containers without subitems
-
- // @todo: check if this is required
- // all container have container export sets
- $all_importers = array();
-
- if(!$parser->getExportSets())
- {
- $this->createDummy($type);
- $import_info = parent::doImportObject($dir,$type);
-
- $all_importers = array_merge($all_importers, $import_info['importers']);
- return $import_info;
- //return $import_info['new_id'];
- }
-
- // Handling containers with subitems
- $first = true;
- foreach($parser->getExportSets() as $set)
- {
- $import_info = parent::doImportObject($dir.DIRECTORY_SEPARATOR.$set['path'],$set['type']);
-
- $all_importers = array_merge($all_importers, $import_info['importers']);
- if($first)
- {
- $ret = $import_info;
- //$ret = $import_info['new_id'];
- $first = false;
- }
- }
- // after container import is finished, call all importers to perform a final processing
- foreach((array) $all_importers as $importer)
- {
- $importer->afterContainerImportProcessing($this->getMapping());
- }
- // end-patch optes_lok_export
-
- return $ret;
- }
-
- /**
- * Create dummy object
- * @param object $a_type
- * @return
- */
- protected function createDummy($a_type)
- {
- global $DIC;
+ // Handling single containers without subitems
+
+ // @todo: check if this is required
+ // all container have container export sets
+ $all_importers = array();
+
+ if (!$parser->getExportSets()) {
+ $this->createDummy($type);
+ $import_info = parent::doImportObject($dir, $type);
+
+ $all_importers = array_merge($all_importers, $import_info['importers']);
+ return $import_info;
+ //return $import_info['new_id'];
+ }
+
+ // Handling containers with subitems
+ $first = true;
+ foreach ($parser->getExportSets() as $set) {
+ $import_info = parent::doImportObject($dir . DIRECTORY_SEPARATOR . $set['path'], $set['type']);
+
+ $all_importers = array_merge($all_importers, $import_info['importers']);
+ if ($first) {
+ $ret = $import_info;
+ //$ret = $import_info['new_id'];
+ $first = false;
+ }
+ }
+ // after container import is finished, call all importers to perform a final processing
+ foreach ((array) $all_importers as $importer) {
+ $importer->afterContainerImportProcessing($this->getMapping());
+ }
+ // end-patch optes_lok_export
+
+ return $ret;
+ }
+
+ /**
+ * Create dummy object
+ * @param object $a_type
+ * @return
+ */
+ protected function createDummy($a_type)
+ {
+ global $DIC;
- $objDefinition = $DIC['objDefinition'];
+ $objDefinition = $DIC['objDefinition'];
- $class_name = "ilObj".$objDefinition->getClassName($a_type);
- $location = $objDefinition->getLocation($a_type);
-
- include_once($location."/class.".$class_name.".php");
- $new = new $class_name();
- $new->setTitle('Import');
- $new->create(true);
- $new->createReference();
- $new->putInTree($this->getMapping()->getTargetId());
- $new->setPermissions($this->getMapping()->getTargetId());
-
- $this->getMapping()->addMapping('Services/Container','objs', 0, $new->getId());
- $this->getMapping()->addMapping('Services/Container','refs', 0,$new->getRefId());
-
- return $new;
-
- }
+ $class_name = "ilObj" . $objDefinition->getClassName($a_type);
+ $location = $objDefinition->getLocation($a_type);
+
+ include_once($location . "/class." . $class_name . ".php");
+ $new = new $class_name();
+ $new->setTitle('Import');
+ $new->create(true);
+ $new->createReference();
+ $new->putInTree($this->getMapping()->getTargetId());
+ $new->setPermissions($this->getMapping()->getTargetId());
+
+ $this->getMapping()->addMapping('Services/Container', 'objs', 0, $new->getId());
+ $this->getMapping()->addMapping('Services/Container', 'refs', 0, $new->getRefId());
+
+ return $new;
+ }
}
-?>
\ No newline at end of file
diff --git a/Services/Export/classes/class.ilImportExportFactory.php b/Services/Export/classes/class.ilImportExportFactory.php
index 08a2b412d44363a825e419a492cc6341f3812107..b9cce08a61300452be808167e76ce72d976735c8 100644
--- a/Services/Export/classes/class.ilImportExportFactory.php
+++ b/Services/Export/classes/class.ilImportExportFactory.php
@@ -3,139 +3,120 @@
/**
* Factory for importer/exporter implementers
- *
+ *
* @author Stefan Meyer